Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash idioms for conditional array append?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"} )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading