How to loop over an array using bash script – Code Example

Total
0
Shares

Get the code to loop over an array using bash script. We will provide 3 ways to loop over an array. You can fetch each element of array or use indexes.

Code Example –

1. Fetching elements of array –

#!/bin/bash

arr=(Cattle feed us milk like a mother and we kill them. What a shame)

for element in "${arr[@]}"; do
    printf '%s\n' "$element"
done

# Output: 
# Cattle
# feed
# us
# milk
# like
# a
# mother
# and
# we
# kill
# them.
# What
# a
# shame

2. Access array values using index (method 1)

#!/bin/bash

arr2=(Do not hurt animals)

for i in "${!arr2[@]}"; do
    printf '%s\n' "${arr2[i]}"
done

# Output:
# Do
# not
# hurt
# animals

3. Access array values using index (method 2)

#!/bin/bash

arr3=(Respect nature)

for ((i=0;i<${#arr3[@]};i++)); do
    printf '%s\n' "${arr3[i]}"
done

# Output:
# Respect
# nature

Inspired from Dylan Araps

Live Demo

Open Live Demo