Handling Unbound Variables
Setting Default Values
One common way to handle unbound variables is to set a default value. This can be done using parameter expansion:
#!/bin/bash
echo "The value of UNSET_VAR is ${UNSET_VAR:-"Variable is not set."}"
In this example, if UNSET_VAR
is not defined, the default value "Variable is not set."
will be used.
Using the set -u
Option
As mentioned earlier, the set -u
option (or set -o nounset
) can be used to make Bash exit immediately when it encounters an unbound variable. This is a recommended practice for writing robust Bash scripts.
#!/bin/bash
set -u
echo "The value of UNSET_VAR is $UNSET_VAR"
If you run this script with an unbound UNSET_VAR
, it will exit with an error message:
./script.sh: line 3: UNSET_VAR: unbound variable
Handling Unbound Variables in Functions
When working with functions, you may need to handle unbound variables passed as arguments. You can do this by using the ${parameter:-default}
syntax:
#!/bin/bash
my_function() {
local var1="${1:-"default value 1"}"
local var2="${2:-"default value 2"}"
echo "var1 = $var1, var2 = $var2"
}
my_function "hello"
my_function "hello" "world"
This will output:
var1 = hello, var2 = default value 2
var1 = hello, var2 = world
Using the set -o pipefail
Option
In addition to the set -u
option, you can also use set -o pipefail
to make Bash exit immediately when any command in a pipeline fails. This can help you catch unbound variables that are used in pipeline commands.
#!/bin/bash
set -o pipefail
echo "The value of UNSET_VAR is $UNSET_VAR" | cat
By combining set -u
and set -o pipefail
, you can create a robust set of options to handle unbound variables in your Bash scripts.