There is no direct method in bash to determine if a variable is set or not. But we can use “parameter expansion” feature provided by bash. The following example script determines if bash variables MYVAR and MYVAR1 are set or not.

#!/bin/bash

MYVAR=hello

if [ -n "${MYVAR+x}" ]; then
echo MYVAR is set
else
echo MYVAR is not set
fi

if [ -n "${MYVAR1+x}" ]; then
echo MYVAR1 is set
else
echo MYVAR1 is not set
fi

Here is the output of above script where MYVAR is set but MYVAR1 is not set.

[neo@techpulp ~]# sh vset.sh
MYVAR is set
MYVAR1 is not set
[neo@techpulp ~]#

However there are multiple ways to determine if a variable is set but contains blank or not.

Method 1:

The following condition determines if a variable contains null string or blank.

if [ "$MYVAR" == "" ]; then
  echo MYVAR is empty
else
  echo MYVAR is not empty
fi

Method 2:

case $MYVAR in '') echo MYVAR is not set;; *) echo MYVAR is set;; esac

Method 3:

if [ ! -n "$MYVAR" ]; then
  echo MYVAR is blank
else
  echo MYVAR is not blank
fi

All the above methods can be applied to check if an environment variable is set or not.