Linux bash provides programmatic features like arrays. Bash array is a useful feature that can be used to store multiple items in a single variable. The bash array can be used to store multiple items and iterate them to read with loops. Different programming languages provide the array or list feature but the bash array feature can be a bit tricky. In this tutorial we examine bash array-like creating bash array, accessing bash array items, updating bash array, etc.
Create Bash Array
In order to create an array in Bash the brackets are used. Every item put between double quotos and separated with spaces. The syntax of the bash array creation is like below.
ARRAY_NAME=("ITEM1" "ITEM2" "ITEM3")
In the following example we will create an array named cities
and put city names as item into this array.
$ cities=("Ankara" "London" "Berlin")
Access Item In Bash Array
Specific bash array item can be accessed by providing its index number inside square brackets. The bash array index numbers start from 0 and step up one by one. This means the first item index number is 0, second item index number is 1 and so on. The syntax of accessing item in a bash array is like below.
VARIABLE=${ARRAY_NAME[INDEX]}
- ARRAY_NAME is the name of the array.
- INDEX is the index number of the array.
- VARIABLE is used to set the specified item in the array.
In the following example we will access the item which index number is 2.
$ city=${cities[2]}
Then we can print the item like below where it is assigned to the variable named $city
.
$ echo $city
Loop/Iterate over Bash Array
An array contains multiple items. These items can be iterated or looped by using loop mechnisms like for loop
or while loop
. In the following example we loop over the array named cities
.
cities=("Ankara" "London" "Berlin")
for i in ${!cities[@]}; do
echo "City name is ${cities[$i]}"
done
City name is Ankara City name is London City name is Berlin