An list in created by using the () characters. In this example, an empty list named fruit is created (the list contains no values).
fruit=()
In this example, an list named fruit is created, and the list contains different types of fruit.
fruit=(apple banana orange grapes)
The echo command will only print the first item in the list .
echo $fruit
In this example, the echo command would only print the first element in the list, "apple".
apple
Here is how to print every element in the list.
echo ${fruit[*]}
Which should return the following.
apple banana orange grapes
for loop
Or, a for loop can be used to iterate over each item in the list, like this.
for item in ${fruit[@]}; do
echo $item
done
Which should return the following.
apple
banana
orange
grape
Index
Lists can also created using index numbers.
fruit[0]=apple
fruit[1]=banana
fruit[3]=orange
fruit[4]=grape
Individual list items can then be printed using the list index number.
echo ${fruit[0]}
echo ${fruit[1]}
echo ${fruit[2]}
echo ${fruit[3]}
Or like this.
echo ${fruit[0]} ${fruit[1]} ${fruit[2]} ${fruit[3]}
Or like this, to print every item in the list.
echo ${fruit[*]}
In this example, each piece of fruit will be printed.
apple
banana
orange
grape
Whitespace in elements
Let's say elements in the list may contain whitespace. In this example, "honeydew melon" contains whitespace. Double quote the elements in the list.
fruit=("apple" "banana" "orange" "grapes" "honeydew melon")
Also double quote the for loop.
for item in "${fruit[@]}"; do
echo $item
done
In this example, each piece of fruit will be printed.
apple
banana
orange
grape
honeydew melon
Count the number of items in an list
This list contains four items.
fruits=(apple banana orange grapes)
The number of items in an list can be printed like this.
echo ${#fruit[*]}
Did you find this article helpful?
If so, consider buying me a coffee over at