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"
Using default values in initialization of array Type[] arr = new Type[capacity]; For example, the following code creates a primitive integer array of size 5 . The array will be auto-initialized with a default value of 0 .
An assignment of the form variable=${value:-default} assigns value to $variable if it is set: otherwise it assigns default to $variable. In the example above, the variable ${PAGER:-more} is expanded to either the value of $PAGER, or if this is not set, to more.
Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.
When an array is created without assigning it any elements, compiler assigns them the default value. Following are the examples: Boolean - false. int - 0.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With