Loop Through Array in Bash

Fumbani Banda Oct 29, 2021
Loop Through Array in Bash

This tutorial loops through an array in bash and displays all values.

Loop Through an Array in Bash

We create an index array with the -a option, which is named cities_array. We loop through ${cities_array[@]}, which contains all the values of the array, and we display each value with the printf command.

declare -a cities_array=("New York" "London" "Moscow")

for city in "${cities_array[@]}"
do
    printf "$city\n"
done

Output:

New York
London
Moscow
Fumbani Banda avatar Fumbani Banda avatar

Fumbani is a tech enthusiast. He enjoys writing on Linux and Python as well as contributing to open-source projects.

LinkedIn GitHub

Related Article - Bash Array

Related Article - Bash Loop