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

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

Unfortunately, this does not work when the default 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 to do this? Please note that changing := to :- does not help.

Another problem is that any solution we get should also work when my_variable already set in advance, so

 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" 
+6
source share
1 answer

To use an array:

 unset my_variable default_value default_value=("ab" 10) my_variable=( "${my_variable[@]:-"${default_value[@]}"}" ) printf "%s\n" "${my_variable[@]}" ab 10 printf "%s\n" "${default_value[@]}" ab 10 

Online demo

According to 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. 
+2
source

Source: https://habr.com/ru/post/979882/


All Articles