George V. Reilly

Bash: Getting and Setting Default Values

Bash has some handy syntax for getting and setting default values. Un­for­tu­nate­ly, it’s a collection of punc­tu­a­tion characters, which makes it hard to Google when you can’t quite remember the syntax.

Getting a default value using ${var:-fallback}:

# set $LOGDIR to $1 if $1 has a value; otherwise set $LOGDIR to "/var/log"
LOGDIR="${1:-/var/log}"

# use $VERSION unless it's empty or unset; fall back to extracting someprog's version num
build_version=${VERSION:-$(someprog --version | sed 's/[^0-9.]*\([0-9.]*\).*/\1/')}

The colon-dash con­struc­tion is known as the dog’s bollocks in typography.

Setting a default value, using ${var:=fallback}:

$ echo $HOME
/Users/georgevreilly
$ echo ${HOME:=/tmp}
/Users/georgevreilly
$ unset HOME
$ echo ${HOME:=/tmp}
/tmp
$ echo $HOME
/tmp
$ cd; pwd
/tmp

Note: := uses the new value in two cases. First, when the shell variable is not set; second, when the variable is set but empty.

If you want to assign the variable only when it’s previously unset, omit the colon, ${var=fallback}.

blog comments powered by Disqus
Review: Blind Justice » « Review: Star Doc