Assigning default values to shell variables with a single command in bash
Categories:
Assigning Default Values to Shell Variables in Bash
Learn how to efficiently assign default values to shell variables in Bash using various parameter expansion techniques, ensuring your scripts are robust and handle unset or null variables gracefully.
In Bash scripting, it's common to encounter situations where a variable might be unset or empty. Directly using such variables can lead to unexpected behavior or errors in your scripts. Bash provides powerful parameter expansion features that allow you to assign default values to variables with a single, concise command, making your scripts more resilient and readable. This article explores the primary methods for achieving this, focusing on their nuances and best use cases.
Understanding Bash Parameter Expansion for Defaults
Bash offers several forms of parameter expansion that are specifically designed for handling default values. These expansions check the state of a variable (whether it's unset or null) and perform an action based on that state. The key operators are ${parameter:-word}
, ${parameter:=word}
, ${parameter:+word}
, and ${parameter:?word}
. Each serves a slightly different purpose, allowing for fine-grained control over variable assignment and error handling.
flowchart TD A[Variable Check] --> B{Is variable unset or null?} B -- Yes --> C{Choose Default Action} C -- Assign if unset/null (:=) --> D[Variable gets default value] C -- Use default if unset/null (:-) --> E[Expression uses default, variable unchanged] C -- Use alternate if set/non-null (:+) --> F[Expression uses alternate, variable unchanged] C -- Error if unset/null (:?) --> G[Script exits with error] B -- No --> H[Variable retains its value]
Decision flow for Bash parameter expansion with default values.
The :-
Operator: Use Default If Unset or Null
The ${parameter:-word}
expansion is one of the most commonly used methods. It evaluates to word
if parameter
is unset or null (empty string). Otherwise, it evaluates to the value of parameter
. Crucially, this operator does not assign the default value back to the variable itself; it only uses the default for the current expression. This is useful when you want to provide a fallback value without permanently altering the variable's state.
# Example 1: Variable is unset
unset MY_VAR
echo "Value: ${MY_VAR:-'default_value'}" # Output: Value: default_value
echo "MY_VAR after: '$MY_VAR'" # Output: MY_VAR after: '' (still unset)
# Example 2: Variable is null (empty string)
MY_VAR=""
echo "Value: ${MY_VAR:-'default_value'}" # Output: Value: default_value
echo "MY_VAR after: '$MY_VAR'" # Output: MY_VAR after: '' (still empty)
# Example 3: Variable is set and non-null
MY_VAR="existing_value"
echo "Value: ${MY_VAR:-'default_value'}" # Output: Value: existing_value
echo "MY_VAR after: '$MY_VAR'" # Output: MY_VAR after: 'existing_value'
Using the :-
operator for temporary default values.
The :=
Operator: Assign Default If Unset or Null
The ${parameter:=word}
expansion is similar to :-
, but with a critical difference: if parameter
is unset or null, word
is assigned as the default value to parameter
and then evaluated. This means the variable itself is modified. This is ideal when you want to ensure a variable always has a value, either its original one or a specified default.
# Example 1: Variable is unset
unset MY_VAR
echo "Value: ${MY_VAR:='default_value'}" # Output: Value: default_value
echo "MY_VAR after: '$MY_VAR'" # Output: MY_VAR after: 'default_value' (now set)
# Example 2: Variable is null (empty string)
MY_VAR=""
echo "Value: ${MY_VAR:='default_value'}" # Output: Value: default_value
echo "MY_VAR after: '$MY_VAR'" # Output: MY_VAR after: 'default_value' (now set)
# Example 3: Variable is set and non-null
MY_VAR="existing_value"
echo "Value: ${MY_VAR:='default_value'}" # Output: Value: existing_value
echo "MY_VAR after: '$MY_VAR'" # Output: MY_VAR after: 'existing_value'
Using the :=
operator to assign a default value to the variable.
:=
operator is particularly useful for setting configuration variables that might be optionally provided by the user or environment, but should always have a sensible fallback.Other Useful Operators: :+
and :?
While :-
and :=
are for defaults, Bash offers two more related operators for different scenarios:
${parameter:+word}
(Use Alternate Value If Set and Non-Null): This expansion evaluates toword
ifparameter
is set and non-null. Otherwise, it evaluates to an empty string. This is useful for providing an alternative value only when a variable is defined.${parameter:?word}
(Error If Unset or Null): Ifparameter
is unset or null,word
is printed to standard error, and the script exits. Otherwise, it evaluates to the value ofparameter
. This is excellent for enforcing that critical variables must be set.
# Using :+
unset MY_VAR
echo "${MY_VAR:+'alternate'}" # Output: (empty line)
MY_VAR="hello"
echo "${MY_VAR:+'alternate'}" # Output: alternate
# Using :? (will cause script to exit if uncommented and MY_VAR is unset/null)
# unset MY_VAR
# echo "${MY_VAR:?'Error: MY_VAR must be set!'}"
MY_VAR="valid"
echo "${MY_VAR:?'Error: MY_VAR must be set!'}" # Output: valid
Examples of :+
and :?
parameter expansions.
:
) from these operators (e.g., ${parameter-word}
) changes their behavior slightly: they only check if the variable is unset, not if it's null (empty string). For most default value scenarios, including the colon is preferred to handle both unset and empty cases.