These are few ways of iterating on bash arrays to read and or modify array’s elements in bash on Linux or Mac. Here are some approaches and code sample for these.
Iterating using values (for in)
We can use for in
loop if we just need to read values.
#!/bin/bash arr=(a b c) for i in ${arr[@]} ; do echo "$i" done
a b c
Env: GNU bash, version 4.2.46
Note that you can put
${arr[@]}
in double quotes also.
Iterate using index
#!/bin/bash arr=(a b c) for ((i=0; i < ${#arr[@]}; i++)) do echo ${arr[$i]} done
a b c
Env: GNU bash, version 4.2.46
Iterate and modify using index
#!/bin/bash arr=(a b c) for ((i=0; i < ${#arr[@]}; i++)) do arr[i]+="..." echo ${arr[$i]} done
a... b... c...
Env: GNU bash, version 4.2.46