Bash null check

From thelinuxwiki
Jump to: navigation, search

The -n operator checks whether the string is not null. Effectively, this will return true for every case except where the string contains no characters. ie:

VAR="hello"
if [ -n "$VAR" ]; then
   echo "VAR is not empty"
fi

Similarly, the -z operator checks whether the string is null. ie:

VAR=""
if [ -z "$VAR" ]; then
   echo "VAR is empty"
fi

Note the spaces around the square brackets. Bash will complain if the spaces are not there.


example using null check to see if a drive is mounted

volume="toshibaHD"
check=$(mount|grep $volume)    
if [ -n "$check" ]
then
  echo "\$check is NOT null"
else
 echo "\$check IS null"
fi