Skip to content

Bash: conditional arguments

Anthony Sottile edited this page Mar 1, 2018 · 2 revisions

A common pitfall in bash is to use a variable as a conditional argument as follows:

if [ -n "${NAME}" ]; then
    arg="--hello=${NAME}"
else
    arg=""
fi

python -c 'import sys; print(sys.argv[1:])' $arg

I'm only using python here to show how the arguments are interpolated

This works fine where NAME doesn't contain spaces:

$ NAME= bash test.sh
[]
$ NAME=Anthony bash test.sh
['--hello=Anthony']

But as soon as you have spaces:

$ NAME='Anthony Sottile' bash test.sh
['--hello=Anthony', 'Sottile']

The correct fix for this in bash is to use an array:

args=()

if [ -n "${NAME}" ]; then
    args+=("--hello=${NAME}")
fi

python -c 'import sys; print(sys.argv[1:])' "${args[@]}"

Success!

$ NAME= bash test.sh
[]
$ NAME=Anthony bash test.sh
['--hello=Anthony']
$ NAME='Anthony Sottile' bash test.sh
['--hello=Anthony Sottile']
Clone this wiki locally