More Bash answers

by Danny
Published 2 min read

How to create, loop over, add to and measure arrays in Bash, how associative arrays work, and why they fail with the old Bash 3.2 that ships with macOS.

The short answer

#

Create an array with parentheses, and always expand it as "${arr[@]}" with the quotes. That gives you one word per element, even when elements contain spaces.


_10
fruits=("apple" "blood orange" "pear")
_10
_10
for fruit in "${fruits[@]}"; do
_10
echo "$fruit"
_10
done
_10
_10
echo "Count: ${#fruits[@]}"
_10
echo "First: ${fruits[0]}"

Why it happens

#

Bash variables are strings by default. If you put a list in a plain string, such as files="a.txt my notes.txt", the shell can only split it on spaces, so my notes.txt turns into two items. Arrays keep each element separate, which is the only safe way to hold a list of file names or arguments.

The expansion syntax is where most bugs come from. $fruits on its own gives you only the first element. ${fruits[*]} joins everything into one string. Unquoted ${fruits[@]} splits elements on spaces again. Only the quoted "${fruits[@]}" keeps every element intact, which is why you will see it everywhere in well-written scripts.

How to fix it

#

Create, read and change indexed arrays


_16
# Create
_16
ports=(3000 3001 3002)
_16
empty=()
_16
declare -a names # explicit, optional
_16
_16
# Read
_16
echo "${ports[1]}" # 3001
_16
echo "${ports[@]}" # all elements
_16
echo "${#ports[@]}" # number of elements
_16
echo "${!ports[@]}" # indexes: 0 1 2
_16
echo "${ports[@]:1:2}" # slice: 3001 3002
_16
_16
# Change
_16
ports+=(4000) # append
_16
ports[0]=8080 # replace
_16
unset 'ports[1]' # remove (leaves a gap in the indexes)

Indexes start at 0. Removing an element with unset does not renumber the rest, so loop over values with "${ports[@]}", or over "${!ports[@]}" when you need the index.

Loop with the index


_10
for i in "${!ports[@]}"; do
_10
echo "$i: ${ports[$i]}"
_10
done

Fill an array from a command

Do not write arr=($(command)), which splits on spaces and expands globs. Read line by line instead.


_10
# Bash 4+
_10
mapfile -t lines < todo.txt
_10
_10
# Works in Bash 3.2 too
_10
lines=()
_10
while IFS= read -r line; do
_10
lines+=("$line")
_10
done < todo.txt

Pass an array as arguments

Arrays are the cleanest way to build up a command's arguments safely.


_10
args=(--verbose --output "build dir")
_10
if [[ $DRY_RUN == 1 ]]; then
_10
args+=(--dry-run)
_10
fi
_10
_10
my-tool "${args[@]}"

Associative arrays (Bash 4+)

Associative arrays map string keys to values. You must declare them with declare -A first, otherwise Bash treats the keys as numbers.


_13
declare -A colours
_13
colours[primary]="blue"
_13
colours["call to action"]="orange"
_13
_13
echo "${colours[primary]}"
_13
_13
for key in "${!colours[@]}"; do
_13
echo "$key = ${colours[$key]}"
_13
done
_13
_13
if [[ -v colours[primary] ]]; then
_13
echo "primary is set"
_13
fi

Keys come back in no particular order. Sort them yourself if order matters.

The macOS caveat

macOS still ships Bash 3.2 at /bin/bash, because later versions use the GPLv3 licence. Its default interactive shell has been zsh since Catalina. On Bash 3.2, declare -A fails with "invalid option", and mapfile, readarray and negative indexes such as ${arr[-1]} are missing.

Check the version you are actually running:


_10
echo "$BASH_VERSION"

If you need Bash 4 or later features, install a newer Bash with Homebrew and point your shebang at it with #!/usr/bin/env bash, so the first bash on the PATH is used. Or keep to indexed arrays and while read loops so the script works everywhere.

Common pitfalls

#
  • Forgetting the quotes. for f in ${files[@]} breaks on any element with a space. Write "${files[@]}".
  • Forgetting the braces. $arr[1] prints the first element followed by the text [1]. Write ${arr[1]}.
  • Using $arr to mean the whole array. It is only element 0.
  • Exporting arrays. Bash cannot export arrays to child processes. Pass them as arguments instead.
  • Empty arrays with set -u****. Bash versions before 4.4 treat "${arr[@]}" on an empty array as an unbound variable error.
  • Running under sh****. Arrays are not part of POSIX sh. Use a Bash shebang.
#

Was this resource helpful?