Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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" 
like image 209
Berk U. Avatar asked Dec 18 '14 20:12

Berk U.


People also ask

How do you create an array with default value?

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 .

How do you assign default values to variables?

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.

How do you set a variable in an array?

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.

What is the default value of an array?

When an array is created without assigning it any elements, compiler assigns them the default value. Following are the examples: Boolean - false. int - 0.


1 Answers

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.
like image 81
anubhava Avatar answered Sep 21 '22 09:09

anubhava