How to check if a variable is set in Bash?

if [ -z ${var+x} ]; 
then
  echo "var is unset";
else
  echo "var is set to '$var'";
fi

where ${var+x} is a parameter expansion which evaluates to nothing if var is unset, and substitutes the string x otherwise.

To check for non-null/non-zero string variable, i.e. if set, use

if [ -n "$1" ]

It’s the opposite of -z. I find myself using -n more than -z.

You would use it like:

if [ -n "$1" ]; then
  echo "You supplied the first parameter!"
else
  echo "First parameter not supplied."
fi

Leave a Reply

Your email address will not be published. Required fields are marked *