2

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
salezica
  • 74,081
  • 25
  • 105
  • 166

3 Answers3

12
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} /
bobah
  • 18,364
  • 2
  • 37
  • 70
6

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.

Toxaris
  • 7,156
  • 1
  • 21
  • 37
  • 2
    "Note that if you call your script with an explicit empty first parameter this might behave different from the code in the question." No, it won't, because you used a colon. If you write `${1-default}`, then it will differentiate between an unset and set but empty parameter. – Roman Cheplyaka Feb 13 '14 at 09:03
  • @RomanCheplyaka, thanks, confirmed this in the manual and edited the answer. – Toxaris Feb 13 '14 at 09:11
0

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
Sir Athos
  • 9,403
  • 2
  • 22
  • 23