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 ...

Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.