Berk U.
Berk U.

Reputation: 7188

How to set the default value of a variable as an array?

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" 

Upvotes: 6

Views: 1804

Answers (1)

anubhava
anubhava

Reputation: 785206

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.

Upvotes: 4

Related Questions