Docs  >   Bash Handbook   >   Arrays

Top

Arrays

Like in other programming languages, an array in bash is a variable that allows you to refer to multiple values. In bash, arrays are also zero-based, that is, the first element in an array has index 0.

When dealing with arrays, we should be aware of the special environment variable IFS. IFS, or Input Field Separator, is the character that separates elements in an array. The default value is an empty space IFS=' '.

Array declaration

In bash you create an array by simply assigning a value to an index in the array variable:

fruits[0]=Apple
fruits[1]=Pear
fruits[2]=Plum

Array variables can also be created using compound assignments such as:

fruits=(Apple Pear Plum)

Array expansion

Individual array elements are expanded similar to other variables:

echo ${fruits[1]} # Pear

The entire array can be expanded by using * or @ in place of the numeric index:

echo ${fruits[*]} # Apple Pear Plum
echo ${fruits[@]} # Apple Pear Plum

There is an important (and subtle) difference between the two lines above: consider an array element containing whitespace:

fruits[0]=Apple
fruits[1]="Desert fig"
fruits[2]=Plum

We want to print each element of the array on a separate line, so we try to use the printf builtin:

printf "+ %s\n" ${fruits[*]}
# + Apple
# + Desert
# + fig
# + Plum

Why were Desert and fig printed on separate lines? Let's try to use quoting:

printf "+ %s\n" "${fruits[*]}"
# + Apple Desert fig Plum

Now everything is on one line — that's not what we wanted! Here's where ${fruits[@]} comes into play:

printf "+ %s\n" "${fruits[@]}"
# + Apple
# + Desert fig
# + Plum

Within double quotes, ${fruits[@]} expands to a separate argument for each element in the array; whitespace in the array elements is preserved.

Array slice

Besides, we can extract a slice of array using the slice operators:

echo ${fruits[@]:0:2} # Apple Desert fig

In the example above, ${fruits[@]} expands to the entire contents of the array, and :0:2 extracts the slice of length 2, that starts at index 0.

Adding elements into an array

Adding elements into an array is quite simple too. Compound assignments are specially useful in this case. We can use them like this:

fruits=(Orange "${fruits[@]}" Banana Cherry)
echo ${fruits[@]} # Orange Apple Desert fig Plum Banana Cherry

The example above, ${fruits[@]} expands to the entire contents of the array and substitutes it into the compound assignment, then assigns the new value into the fruits array mutating its original value.

Deleting elements from an array

To delete an element from an array, use the unset command:

unset fruits[0]
echo ${fruits[@]} # Apple Desert fig Plum Banana Cherry