Bash: Error `Unbound variable' when appending to empty array

From FVue
Jump to: navigation, search

Problem

I have defined strict bash settings:

set -e  # Exit on error
set -u  # Trigger error when expanding unset variables

But now I get the error bash: varname[@]: Unbound variable when I execute the code below:

$ set -u
$ t=( "${t[@]}" foo )
bash: t: unbound variable

Declaring the array in advance with (declare -a varname) doesn't help:

$ set -u
$ declare -a t
$ t=( "${t[@]}" foo )
-bash: t[@]: unbound variable

Setting the variable to an empty array (t=( )) doesn't help either:

$ set -u
$ t=( )
$ t=( "${t[@]}" foo )
-bash: t[@]: unbound variable

Solution 1: Dash (-) parameter expansion

Bash offers parameter expansion for unset variables, e.g.: ${varname-}. The bash manual - search for "Parameter expansion" - says the dash (-) has the following effect:

"If parameter is unset, substitute with empty value."

Using the dash (-) in ${t[@]-} prevents the "unbound variable" error:

$ set -u
$ t=( "${t[@]-}" foo )
$

Solution 2: Set last item specifically

Instead of appending one element, set the last item specifically, without any "unbound variable" error:

$ set -u
$ t[${#t[*]}]=foo
$

See also

Bash: Append to array using while-loop
Best practice for appending multiple values to an existing array
Advanced Bash-Scripting Guide: Arrays
Many useful examples concerning arrays in bash

Comments

blog comments powered by Disqus