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_var:-}" ]]; then
my_array+=( "${my_var}" )
fi
I’m asking because I’m trying to clean up some code that does this instead:
my_array+=( ${my_var:-} )
which is a hack that "works" to conditionally append the value of my_var
to my_array
only if my_var
is non-null, 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_var:-}" ]] && my_array+=( "${my_var}" )
is there a way to conditionally append only non-null values that is terse but idiomatic and clear?
>Solution :
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 not add it if it is undefined or defined but empty use
my_array+=( ${my_var:+"$my_var"} )