How can I set a default value for a bash variable in a concise, idiomatic way? This just looks ugly:
if [[ ! -z "$1" ]]; then
option="$1"
else
option="default"
fi
Join Stack Overflow to learn, share knowledge, and build your career.
default value : ${parameter:-word} \
assign default value : ${parameter:=word} |_ / if unset or null -
error if empty/unset : ${parameter:?mesg} | \ use no ":" for unset only
use word unless empty/unset : ${parameter:+word} /
You can use:
option=${1:-default}
This sets option to the first command line parameter if a first command line parameter was given and not null. Otherwise, it sets option to default. See Bash reference manual for the details on parameter expansion and some useful variants of this form.
${1-default}
, then it will differentiate between an unset and set but empty parameter.
– Roman Cheplyaka
Feb 13 '14 at 9:03
For uses other than assigning a default value, which Toxaris already covered, it's worth mentioning that there is a reverse test for -z
, so instead of
if [[ ! -z "$1" ]]; then
do_something
fi
you can simply write:
if [ -n "$1" ]; then
do_something
fi
and if there is no else
branch, you can shorten it to:
[ -n "$1" ] && do_something
set -e
is concerned, [...] && command
is the same as if [...]; then command; fi
. The [...]
command can safely fail, and command
will exit the shell if it runs and fails.
– chepner
Feb 13 '14 at 14:26