O'Reilly logo

Shell Scripting: Expert Recipes for Linux, Bash, and More by Steve Parker

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Manipulating Arrays

The fact that arrays are structurally different from other variables means that some new syntax is required to manipulate arrays. Wherever possible, doing things to arrays is syntactically very similar to doing the equivalent thing to a string, but there are instances where that syntax is not flexible enough.

Copying an Array

Copying one array to another is simple. It is important for quoting and spacing that the ${array[@]} format (rather than ${array[*]}) is used, and also that double quotes are put around the whole construct. These demonstrations are probably the clearest way to show what can happen when other forms are used.

activities=( swimming "water skiing" canoeing "white-water rafting" surfing )for act in ${activities[@]}do
>   echo "Activity: $act"done
Activity: swimming
Activity: water
Activity: skiing
Activity: canoeing
Activity: white-water
Activity: rafting
Activity: surfing
$

What happened here is that because there were no double quotes around the list, “swimming,” “water,” and “skiing” were all treated as separate words. Placing double quotes around the whole thing fixes this:

for act in "${activities[@]}"do
>   echo "Activity: $act"done
Activity: swimming
Activity: water skiing
Activity: canoeing
Activity: white-water rafting
Activity: surfing
$

Similarly, the * is not suitable either with or without quotes. Without quotes, it does the same as the @ symbol. With quotes, the whole array is boiled down into a single ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required