Bash arrays
===========
---
date: "2013-10-13"
markdown_options: "-markdown_in_html_blocks"
---
Way too many people don't understand Bash arrays. Many of them argue
that if you need arrays, you shouldn't be using Bash. If we reject
the notion that one should never use Bash for scripting, then thinking
you don't need Bash arrays is what I like to call "wrong". I don't
even mean real scripting; even these little stubs in `/usr/bin`:
#!/bin/sh
java -jar /…/something.jar $* # WRONG!
Command line arguments are exposed as an array, that little `$*` is
accessing it, and is doing the wrong thing (for the lazy, the correct
thing is `-- "$@"`). Arrays in Bash offer a safe way preserve field
separation.
One of the main sources of bugs (and security holes) in shell scripts
is field separation. That's what arrays are about.
What? Field separation?
------------------------
Field separation is just splitting a larger unit into a list of
"fields". The most common case is when Bash splits a "simple command"
(in the Bash manual's terminology) into a list of arguments.
Understanding how this works is an important prerequisite to
understanding arrays, and even why they are important.
Dealing with lists is something that is very common in Bash scripts;
from dealing with lists of arguments, to lists of files; they pop up a
lot, and each time, you need to think about how the list is
separated. In the case of `$PATH`, the list is separated by colons.
In the case of `$CFLAGS`, the list is separated by whitespace. In the
case of actual arrays, it's easy, there's no special character to
worry about, just quote it, and you're good to go.
Bash word splitting
-------------------
When Bash reads a "simple command", it splits the whole thing into a
list of "words". "The first word specifies the command to be
executed, and is passed as argument zero. The remaining words are
passed as arguments to the invoked command." (to quote `bash(1)`)
It is often hard for those unfamiliar with Bash to understand when
something is multiple words, and when it is a single word that just
contains a space or newline. To help gain an intuitive understanding,
I recommend using the following command to print a bullet list of
words, to see how Bash splits them up:
printf ' -> %s\n' words… -> word one
-> multiline
word
-> third word
In a simple command, in absence of quoting, Bash separates the "raw"
input into words by splitting on spaces and tabs. In other places,
such as when expanding a variable, it uses the same process, but
splits on the characters in the `$IFS` variable (which has the default
value of space/tab/newline). This process is, creatively enough,
called "word splitting".
In most discussions of Bash arrays, one of the frequent criticisms is
all the footnotes and "gotchas" about when to quote things. That's
because they usually don't set the context of word splitting.
**Double quotes (`"`) inhibit Bash from doing word splitting.**
That's it, that's all they do. Arrays are already split into words;
without wrapping them in double quotes Bash re-word splits them,
which is almost *never* what you want; otherwise, you wouldn't be
working with an array.
Normal array syntax
-------------------
Setting an array
words… is expanded and subject to word splitting
based on $IFS.
array=(words…)
Set the contents of the entire array.
array+=(words…)
Appends words… to the end of the array.
array[n]=word
Sets an individual entry in the array, the first entry is at
n=0.
Now, for accessing the array. The most important things to
understanding arrays is to quote them, and understanding the
difference between `@` and `*`.
Getting an entire array
Unless these are wrapped in double quotes, they are subject to
word splitting, which defeats the purpose of arrays.
I guess it's worth mentioning that if you don't quote them, and
word splitting is applied, @ and *
end up being equivalent.
With *, when joining the elements into a single
string, the elements are separated by the first character in
$IFS, which is, by default, a space.
"${array[@]}"
Evaluates to every element of the array, as a separate
words.
"${array[*]}"
Evaluates to every element of the array, as a single
word.
It's really that simple—that covers most usages of arrays, and most of
the mistakes made with them.
To help you understand the difference between `@` and `*`, here is a
sample of each:
@
*
Input:
#!/bin/bash
array=(foo bar baz)
for item in "${array[@]}"; do
echo " - <${item}>"
done
Input:
#!/bin/bash
array=(foo bar baz)
for item in "${array[*]}"; do
echo " - <${item}>"
done
Output:
- <foo>
- <bar>
- <baz>
Output:
- <foo bar baz>
In most cases, `@` is what you want, but `*` comes up often enough
too.
To get individual entries, the syntax is
${array[n]}, where n starts at 0.
Getting a single entry from an array
Also subject to word splitting if you don't wrap it in
quotes.
"${array[n]}"
Evaluates to the nth entry of the
array, where the first entry is at n=0.
To get a subset of the array, there are a few options:
Getting subsets of an array
Substitute * for @ to get the subset
as a $IFS-separated string instead of separate
words, as described above.
Again, if you don't wrap these in double quotes, they are
subject to word splitting, which defeats the purpose of
arrays.
"${array[@]:start}"
Evaluates to the entries from n=start to the end
of the array.
"${array[@]:start:count}"
Evaluates to count entries, starting at
n=start.
"${array[@]::count}"
Evaluates to count entries from the beginning of
the array.
Notice that `"${array[@]}"` is equivalent to `"${array[@]:0}"`.
Getting the length of an array
The is the only situation with arrays where quoting doesn't
make a difference.
True to my earlier statement, when unquoted, there is no
difference between @ and *.
${#array[@]} or ${#array[*]}
Evaluates to the length of the array
Argument array syntax
---------------------
Accessing the arguments is mostly that simple, but that array doesn't
actually have a variable name. It's special. Instead, it is exposed
through a series of special variables (normal variables can only start
with letters and underscore), that *mostly* match up with the normal
array syntax.
Setting the arguments array, on the other hand, is pretty different.
That's fine, because setting the arguments array is less useful
anyway.
Accessing the arguments array
Individual entries
${array[0]}
$0
${array[1]}
$1
…
${array[9]}
$9
${array[10]}
${10}
…
${array[n]}
${n}
Subset arrays (array)
"${array[@]}"
"${@:0}"
"${array[@]:1}"
"$@"
"${array[@]:pos}"
"${@:pos}"
"${array[@]:pos:len}"
"${@:pos:len}"
"${array[@]::len}"
"${@::len}"
Subset arrays (string)
"${array[*]}"
"${*:0}"
"${array[*]:1}"
"$*"
"${array[*]:pos}"
"${*:pos}"
"${array[*]:pos:len}"
"${*:pos:len}"
"${array[*]::len}"
"${*::len}"
Array length
${#array[@]}
$# + 1
Setting the array
array=("${array[0]}" words…)
set -- words…
array=("${array[0]}" "${array[@]:2}")
shift
array=("${array[0]}" "${array[@]:n+1}")
shift n
Did you notice what was inconsistent? The variables `$*`, `$@`, and
`$#` behave like the n=0 entry doesn't exist.
Inconsistencies
@ or *
"${array[@]}"
→
"${array[@]:0}"
"${@}"
→
"${@:1}"
#
"${#array[@]}"
→
length
"${#}"
→
length-1
These make sense because argument 0 is the name of the script—we
almost never want that when parsing arguments. You'd spend more code
getting the values that it currently gives you.
Now, for an explanation of setting the arguments array. You cannot
set argument n=0. The `set` command is used to manipulate
the arguments passed to Bash after the fact—similarly, you could use
`set -x` to make Bash behave like you ran it as `bash -x`; like most
GNU programs, the `--` tells it to not parse any of the options as
flags. The `shift` command shifts each entry n spots to the
left, using n=1 if no value is specified; and leaving
argument 0 alone.
But you mentioned "gotchas" about quoting!
------------------------------------------
But I explained that quoting simply inhibits word splitting, which you
pretty much never want when working with arrays. If, for some odd
reason, you do what word splitting, then that's when you don't quote.
Simple, easy to understand.
I think possibly the only case where you do want word splitting with
an array is when you didn't want an array, but it's what you get
(arguments are, by necessity, an array). For example:
# Usage: path_ls PATH1 PATH2…
# Description:
# Takes any number of PATH-style values; that is,
# colon-separated lists of directories, and prints a
# newline-separated list of executables found in them.
# Bugs:
# Does not correctly handle programs with a newline in the name,
# as the output is newline-separated.
path_ls() {
local IFS dirs
IFS=:
dirs=($@) # The odd-ball time that it needs to be unquoted
find -L "${dirs[@]}" -maxdepth 1 -type f -executable \
-printf '%f\n' 2>/dev/null | sort -u
}
Logically, there shouldn't be multiple arguments, just a single
`$PATH` value; but, we can't enforce that, as the array can have any
size. So, we do the robust thing, and just act on the entire array,
not really caring about the fact that it is an array. Alas, there is
still a field-separation bug in the program, with the output.
I still don't think I need arrays in my scripts
-----------------------------------------------
Consider the common code:
ARGS=' -f -q'
…
command $ARGS # unquoted variables are a bad code-smell anyway
Here, `$ARGS` is field-separated by `$IFS`, which we are assuming has
the default value. This is fine, as long as `$ARGS` is known to never
need an embedded space; which you do as long as it isn't based on
anything outside of the program. But wait until you want to do this:
ARGS=' -f -q'
…
if [[ -f "$filename" ]]; then
ARGS+=" -F $filename"
fi
…
command $ARGS
Now you're hosed if `$filename` contains a space! More than just
breaking, it could have unwanted side effects, such as when someone
figures out how to make `filename='foo --dangerous-flag'`.
Compare that with the array version:
ARGS=(-f -q)
…
if [[ -f "$filename" ]]; then
ARGS+=(-F "$filename")
fi
…
command "${ARGS[@]}"
What about portability?
-----------------------
Except for the little stubs that call another program with `"$@"` at
the end, trying to write for multiple shells (including the ambiguous
`/bin/sh`) is not a task for mere mortals. If you do try that, your
best bet is probably sticking to POSIX. Arrays are not POSIX; except
for the arguments array, which is; though getting subset arrays from
`$@` and `$*` is not (tip: use `set --` to re-purpose the arguments array).
Writing for various versions of Bash, though, is pretty do-able.
Everything here works all the way back in bash-2.0 (December 1996),
with the following exceptions:
* The `+=` operator wasn't added until Bash 3.1.
* As a work-around, use
array[${#array[*]}]=word to append a
single element.
* Accessing subset arrays of the arguments array is inconsistent if
pos=0 in ${@:pos:len}.
* In Bash 2.x and 3.x, it works as expected, except that argument
0 is silently missing. For example `${@:0:3}` gives arguments 1
and 2; where `${@:1:3}` gives arguments 1, 2, and 3. This means
that if pos=0, then only len-1 arguments
are given back.
* In Bash 4.0, argument 0 can be accessed, but if
pos=0, then it only gives back len-1
arguments. So, `${@:0:3}` gives arguments 0 and 1.
* In Bash 4.1 and higher, it works in the way described in the
main part of this document.
Now, Bash 1.x doesn't have arrays at all. `$@` and `$*` work, but
using `:` to select a range of elements from them doesn't. Good thing
most boxes have been updated since 1996!