Assigning default values to shell variables with a single command in bash

bash, shell

Solution

Very close to what you posted, actually. You can use something called Bash parameter expansion to accomplish this.

To get the assigned value, or `default` if it's missing:

FOO="${VARIABLE:-default}"  # FOO will be assigned 'default' value if VARIABLE not set or null.
# The value of VARIABLE remains untouched.

To do the same, as well as assign `default` to `VARIABLE`:

FOO="${VARIABLE:=default}"  # If VARIABLE not set or null, set it's value to 'default'. 
# Then that value will be assigned to FOO

Problem

I have a whole bunch of tests on variables in a bash (3.00) shell script where if the variable is not set, then it assigns a default, e.g.: ``` if [ -z "${VARIABLE}" ]; then FOO='default' else FOO=${VARIABLE} fi ``` I seem to recall there's some syntax to doing this in one line, something resembling a ternary operator, e.g.: ``` FOO=${ ${VARIABLE} : 'default' } ``` (though I know that won't work...) Am I crazy, or does something like that exist?

Original source

Related problems