Knowledgebase

Find frequently asked questions and setup guides by searching or by browsing the categories.

Create an Array

servers=(web1 web2 db1)
servers+=(cache1)
echo "${servers[0]}"
echo "${servers[@]}"

Elements are separated by spaces, with no commas and no spaces around =. Quote elements that contain spaces: files=("my file.txt" notes.txt). += appends one or more elements. The braces in ${servers[0]} are required: without them Bash reads $servers followed by the text [0].

Read Elements

ExpressionGives
"${a[0]}"First element
"${a[-1]}"Last element
"${a[@]}"All elements
${#a[@]}Number of elements
${!a[@]}All indices
"${a[@]:1:2}"Two elements from index 1

A plain $a is the same as ${a[0]}, which is a common source of scripts that only ever handle the first item.

Why the Quotes Matter

files=("my report.pdf" "notes.txt")

for f in ${files[@]}; do echo "$f"; done      # 3 lines: my, report.pdf, notes.txt
for f in "${files[@]}"; do echo "$f"; done    # 2 lines, names intact

Unquoted, every element is split on spaces again. "${files[@]}" keeps each element as one word. "${files[*]}" joins all elements into one string, which suits printing but not looping.

Loop over an Array

for host in "${servers[@]}"; do
    ping -c 1 -W 2 "$host" > /dev/null && echo "$host is up"
done

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

The second loop walks the indices, which helps when you need the position as well. The loop forms are covered in Bash for loop.

Change and Remove Elements

servers[1]=web3               # replace one element
unset 'servers[0]'            # remove one element
servers=("${servers[@]}")     # renumber from 0
unset servers                 # delete the whole array

After unset on one element the other indices stay as they were, so the array has a gap. Copying the array into itself, as in the third line, numbers it from 0 again. Quote 'servers[0]' so the shell does not read the brackets as a file name pattern.

Associative Arrays

declare -A ports=(
    [ssh]=22
    [http]=80
    [https]=443
)
ports[mysql]=3306

echo "${ports[ssh]}"
for name in "${!ports[@]}"; do
    echo "$name uses port ${ports[$name]}"
done

declare -A is required. Without it, Bash creates an indexed array and reads each key as an arithmetic expression; a plain word that is not a set variable counts as 0, so the values overwrite each other. Keys come back in no fixed order; pipe the output through sort when the order matters.

Read Lines into an Array

mapfile -t lines < /etc/hosts
echo "${#lines[@]} lines"

mapfile -t users < <(cut -d: -f1 /etc/passwd)

mapfile, also called readarray, puts one line in each element. -t removes the line break from each one. The second form reads the output of a command through process substitution.

Split a String

csv="web1,web2,db1"
IFS=, read -r -a hosts <<< "$csv"
echo "${hosts[1]}"    # web2

Setting IFS in front of read changes the separator for that one command only. -a stores the fields in an array.

Arrays Need Bash

On Debian and Ubuntu, /bin/sh is dash, which has no arrays. A script that starts with #!/bin/sh, or is started with sh script.sh, fails with a syntax error at the first array. Start the file with #!/bin/bash and run it with bash script.sh or ./script.sh; see how to write and run a Bash script. In plain sh, the argument list "$@" is the only list you have. How Bash differs from other shells is covered in what is Bash, and reusable blocks of code in Bash functions.

Was this answer helpful?
Loading...