Bash Shell: Find Out If a Variable Is Set or Not

In bash shell, you can check if a variable is set or not using the following syntax:

if [ -z "$VARNAME" ]; then
echo "Variable VARNAME is not set."
else
echo "Variable VARNAME is set to: $VARNAME"
fi

Here, the -z option is used with the [ (test) command to check if the value of the variable VARNAME is an empty string (i.e. not set). If the value is empty, the if block will be executed and the message “Variable VARNAME is not set.” will be displayed. If the value is not empty, the else block will be executed and the message “Variable VARNAME is set to: <value of VARNAME>” will be displayed.

You can also use the ${VARNAME:+set} syntax to check if a variable is set or not:

if [ "${VARNAME+set}" = "set" ]; then
echo "Variable VARNAME is set to: $VARNAME"
else
echo "Variable VARNAME is not set."
fi

This syntax uses the parameter expansion feature of bash to check if the variable VARNAME is set. If the variable is set, the expression "${VARNAME+set}" will expand to the string "set", and the if block will be executed. If the variable is not set, the expression will expand to an empty string, and the else block will be executed.

Leave a Comment