Bash – iterate over array

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.3.11

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.3.11

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.3.11
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments