In this post, I'll show you how to use for loop on array of strings in bash. We will see several bash examples of foor loops.
for loop on array
In bash, we can use a for loop to iterate over an array of elements:
for i in US UK ID CH; do
echo "$i"
done
This prints each element of the array on a new line:
US
UK
ID
CH
for loop on array - variable
Alternatively we can define array as variable and loop on it:
arr=("BR" "CH" "ID")
for i in "${arr[@]}"
do
echo "$i"
done
BR
CH
ID
The ${arr[@]}
syntax is used to access all elements of the array.
The "$i" inside the loop body refers to the current element of the array (processed in each iteration).
for loop on array - script
To create a shell script to loop over the list of strings we use this syntax:
#!/bin/bash
arr=("BR" "CH" "ID")
for mystr in "${arr[@]}"; do echo "$mystr"; done
We can save it as script file: script.sh
and run it by:
./script.sh
BR
CH
ID
In the last section you can find if you face error: bash array Syntax error: "(" unexpected
for loop on array - append items
To append elements to an array and loop over it in bash use syntax: newarr=("${arr[@]}" "UK")
:
#!/bin/bash
arr=("BR" "CH" "ID")
newarr=("${arr[@]}" "UK")
for mystr in "${newarr[@]}"; do echo "$mystr"; done
This will output:
BR
CH
ID
UK
bash array Syntax error: "(" unexpected
IN some terminals if you run this as bash script it may result into error:
bash array Syntax error: "(" unexpected
The error is caused by:
- starting the script with
#!/bin/sh
#!/bin/bash
- running the script with:
sh script.sh
To fix error bash array Syntax error: "(" unexpected
remove the start and run it with: ./script.sh