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.
_10fruits=("apple" "blood orange" "pear")_10_10for fruit in "${fruits[@]}"; do_10 echo "$fruit"_10done_10_10echo "Count: ${#fruits[@]}"_10echo "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_16ports=(3000 3001 3002)_16empty=()_16declare -a names # explicit, optional_16_16# Read_16echo "${ports[1]}" # 3001_16echo "${ports[@]}" # all elements_16echo "${#ports[@]}" # number of elements_16echo "${!ports[@]}" # indexes: 0 1 2_16echo "${ports[@]:1:2}" # slice: 3001 3002_16_16# Change_16ports+=(4000) # append_16ports[0]=8080 # replace_16unset '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
_10for i in "${!ports[@]}"; do_10 echo "$i: ${ports[$i]}"_10done
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+_10mapfile -t lines < todo.txt_10_10# Works in Bash 3.2 too_10lines=()_10while IFS= read -r line; do_10 lines+=("$line")_10done < todo.txt
Pass an array as arguments
Arrays are the cleanest way to build up a command's arguments safely.
_10args=(--verbose --output "build dir")_10if [[ $DRY_RUN == 1 ]]; then_10 args+=(--dry-run)_10fi_10_10my-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.
_13declare -A colours_13colours[primary]="blue"_13colours["call to action"]="orange"_13_13echo "${colours[primary]}"_13_13for key in "${!colours[@]}"; do_13 echo "$key = ${colours[$key]}"_13done_13_13if [[ -v colours[primary] ]]; then_13 echo "primary is set"_13fi
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:
_10echo "$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
$arrto 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 POSIXsh. Use a Bash shebang.
Related reading
#Was this resource helpful?