How to check if bash variable defined in script

You can check if a variable is defined in a bash script by using the “if [ -z ${var} ]” or “if [ -v var ]” command.

For example, if you want to check if a variable named “var” is defined, you can use:

if [ -z "${var}" ]; then
echo "var is not defined"
else
echo "var is defined"
fi

or

if [ -v var ]; then
echo "var is defined"
else
echo "var is not defined"
fi

The first example uses the “-z” flag, which checks if the variable’s length is zero. If the variable is not defined, the length will be zero, and the “if” statement will evaluate to true.

The second example uses the “-v” flag, which checks if the variable is defined or not.

Leave a Comment