To check if a variable is defined in a Bash script, you can use the -v option of the test command. For example:
if test -v MYVAR; then echo "MYVAR is defined" else echo "MYVAR is not defined" fi
Alternatively, you can use the ${VARNAME+x} expansion, which returns x if VARNAME is defined, and an empty string if VARNAME is not defined. For example:
if [ -n "${MYVAR+x}" ]; then
echo "MYVAR is defined"
else
echo "MYVAR is not defined"
fi
Note that both of these approaches will return true if the variable is defined, even if its value is an empty string. To check if the variable is defined and has a non-empty value, you can use the -n option of the test command, or the -z string comparison operator:
if test -n "$MYVAR"; then echo "MYVAR is defined and has a non-empty value" else echo "MYVAR is not defined or has an empty value" fi
if [ -z "$MYVAR" ]; then echo "MYVAR is not defined or has an empty value" else echo "MYVAR is defined and has a non-empty value" fi