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

Solution 1:

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}"  # If variable not set or null, use default.
# If VARIABLE was unset or null, it still is after this (no assignment done).

Or to assign default to VARIABLE at the same time:

FOO="${VARIABLE:=default}"  # If variable not set or null, set it to default.

Solution 2:

For command line arguments:

VARIABLE="${1:-$DEFAULTVALUE}"

which assigns to VARIABLE the value of the 1st argument passed to the script or the value of DEFAULTVALUE if no such argument was passed. Quoting prevents globbing and word splitting.

Solution 3:

If the variable is same, then

: "${VARIABLE:=DEFAULT_VALUE}"

assigns DEFAULT_VALUE to VARIABLE if not defined. The double quotes prevent globbing and word splitting.

Also see Section 3.5.3, Shell Parameter Expansion, in the Bash manual.

Solution 4:

To answer your question and on all variable substitutions

echo "${var}"
echo "Substitute the value of var."
    

echo "${var:-word}"
echo "If var is null or unset, word is substituted for var. The value of var does not change."
    

echo "${var:=word}"
echo "If var is null or unset, var is set to the value of word."
    

echo "${var:?message}"
echo "If var is null or unset, message is printed to standard error. This checks that variables are set correctly."
    

echo "${var:+word}"
echo "If var is set, word is substituted for var. The value of var does not change."

You can escape the whole expression by putting a \ between the dollar sign and the rest of the expression.

echo "$\{var}"