Bash Array of Strings Tutorial

Bash script provides the array data structure in order to store multiple items in a single variable. Multiple strings can be stored inside an array which is also called as array of strings . In this tutorial, we examine how to define or create an array of strings by accessing and looping them in bash.

Create Bash Array of Strings

Bash array of strings can be created with the following syntax. The array is created using brackets and putting string items inside it.

ARRAY_NAME = (STRING STRING STRING)

In the following example, we create an array named cities which contains multiple city names as strings.

cities=("London" "Berlin" "Istanbul")

Access Bash Array of Strings

Bash array can be accessed by using the index number of the item. The syntax of specifying the index number for an array item is as below.

${ARRAY_NAME[INDEX]}
  • ARRAY_NAME is the name of the array we want to access its item.
  • INDEX is the index number of the item we want to access.

In the following example, we access the items of the array named “cities”.

cities=("London" "Berlin" "Istanbul")

echo ${cities[0]}

echo ${cities[1]}

echo ${cities[2]}
London
Berlin
Istanbul

Iterate(Loop) In Bash Array of Strings

The for loop can be used to iterate over the bash array of strings. From the start, every item is iterated one by one.

cities=("London" "Berlin" "Istanbul")

for city in ${cities[@]}; do
   echo $city
done 

Iterate(Loop) Using Index In Bash Array of Strings

In the following example, we iterate over an array of strings using the index numbers. We increase the index number in every step and use the new index number in order to print the specified element.

cities=("London" "Berlin" "Istanbul")

for i in ${!cities[@]}; do
  echo "${cities[$i]}"
done
See also  Make Bash Shell Safe with "set -euxo pipefail"

Leave a Comment