How to check if a Bash variable is set or not
In Category Bash
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.
>> There is no direct method in bash to determine if a variable is set or not.
Really?
See snippet from the bash website below …
${parameter=default}, ${parameter:=default}
If parameter not set, set it to default.
Both forms nearly equivalent. The : makes a difference only when $parameter has been declared and is null, [1] as above.