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