6

I recently discovered that it is possible to have Bash set the a variable to a default value when that variable is not set (as described in this post).

Unfortunately, this does not seem to work when the default value is an array. As an example consider,

default_value=(0 1 2 3 4)

my_variable=${my_variable:=("${default_value[@]}")}

echo ${my_variable[0]}
(0 a  2 3 4) #returns array :-(

echo ${my_variable[1])
#returns empty

Does anyone know how do this? Note that changing := to :- does not help.

Another issue is that whatever solution we get should also work for when my_variable already set beforehand as well, so that

my_variable=("a" "b" "c")
default_value=(0 1 2 3 4)

my_variable=${my_variable:=("${default_value[@]}")}

echo ${my_variable[0]}
"a" 

echo ${my_variable[1]}
"b" 

echo ${my_variable[2]}
"c" 
Community
  • 1
  • 1
Berk U.
  • 7,018
  • 6
  • 44
  • 69
  • 1
    It's a bit odd to even want to use `:=` with an array variable, since the `:` part seems to presuppose that it's a string variable? – ruakh Dec 18 '14 at 20:53

1 Answers1

4

To make it array use:

unset my_variable default_value
default_value=("a b" 10)
my_variable=( "${my_variable[@]:-"${default_value[@]}"}" )

printf "%s\n" "${my_variable[@]}"
a b
10

printf "%s\n" "${default_value[@]}"
a b
10

Online Demo

As per man bash:

${parameter:-word}
   Use Default Values. If parameter is unset or null, the expansion of word is substituted.
   Otherwise, the value of parameter is substituted.
anubhava
  • 761,203
  • 64
  • 569
  • 643