I am trying to figure out if there is a shorter way in bash of conditionally appending the value of a variable to an array only if the value is non-null.
I believe the following is correct, but kind of "wordy"
my_array=()
if [[ "${my_first_var:-}" ]]; then
my_array+=( "${my_first_var}" )
fi
if [[ "${my_second_var:-}" ]]; then
my_array+= ( "${my_second_var}" )
fi
I'm asking because I'm trying to clean up some code that does this instead:
my_array+=( ${my_first_var:-} ${my_second_var:-} )
which is a hack that "works" to conditionally append only the non-null values to my_array
, and is nice because it uses array interpolation, but has the problem that if the string in my_var
contains a space (or whatever IFS
is set to) it does something very unintended (appends multiple elements into the array).
I was thinking of this maybe, but I'm not sure if my intent is sufficiently clear.
[[ "${my_first_var:-}" ]] && my_array+=( "${my_first_var}" )
[[ "${my_second_var:-}" ]] && my_array+=( "${my_second_var}" )
is there a way to conditionally append only non-null values that is terse but is idiomatic and clear?
One option is
my_array+=( ${my_var+"$my_var"} )
That will add the value of my_var
to the array if it is defined, even if it is empty. If you want to add it only if it is defined and not empty, use
my_array+=( ${my_var:+"$my_var"} )