Monday, July 25, 2022

[SOLVED] Test if a variable is set in Bash when using "set -o nounset"

Issue

The following code exits with a unbound variable error. How can I fix this, while still using the set -o nounset option?

#!/bin/bash

set -o nounset

if [ ! -z ${WHATEVER} ];
 then echo "yo"
fi

echo "whatever"

Solution

#!/bin/bash

set -o nounset


VALUE=${WHATEVER:-}

if [ ! -z ${VALUE} ];
 then echo "yo"
fi

echo "whatever"

In this case, VALUE ends up being an empty string if WHATEVER is not set. We're using the {parameter:-word} expansion, which you can look up in man bash under "Parameter Expansion".



Answered By - Angelom
Answer Checked By - Marie Seifert (WPSolving Admin)