Loop through an array of strings in Bash? Loop through an array of strings in Bash? bash bash

Loop through an array of strings in Bash?


You can use it like this:

## declare an array variabledeclare -a arr=("element1" "element2" "element3")## now loop through the above arrayfor i in "${arr[@]}"do   echo "$i"   # or do whatever with individual element of the arraydone# You can access them using echo "${arr[0]}", "${arr[1]}" also

Also works for multi-line array declaration

declare -a arr=("element1"                 "element2" "element3"                "element4"                )


That is possible, of course.

for databaseName in a b c d e f; do  # do something like: echo $databaseNamedone 

See Bash Loops for, while and until for details.


None of those answers include a counter...

#!/bin/bash## declare an array variabledeclare -a array=("one" "two" "three")# get length of an arrayarraylength=${#array[@]}# use for loop to read all values and indexesfor (( i=0; i<${arraylength}; i++ ));do  echo "index: $i, value: ${array[$i]}"done

Output:

index: 0, value: oneindex: 1, value: twoindex: 2, value: three