سؤال

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
هل كانت مفيدة؟

المحلول

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.

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top