Calvin's Blog

Bash: Arrays and how to iterate over them

∙ scripting∙ bash
article meme

Introduction

Arrays in bash are a powerful tool for working with multiple items. They lend themselves to iteration via loops.

Declaring Arrays In Bash

Declaring an array in bash is as follows:

#!/bin/bash

my_array=("one" "two" "three")

Notice the use of parenthesis to wrap the items and using spaces to delimit the items in the array.

Iterate Over An Array

You can iterate over an array using shell parameter expansion and special characters like @.

#!/bin/bash

# declare array
my_array=("one" "two" "three")

# get number of items in array
echo "array contains ${#my_array[@]} items"

# expand all items in array
echo "${my_array[@]}"

# using expanded array for items to loop over
for item in ${my_array[@]}; do
  echo "found: $item"
done

# the loop above is equivalent to this
for item in "one" "two" "three"; do
  echo "found: $item"
done