Bash Shell: Find Out If a Variable Is Set or Not

Bash Shell: Find Out If a Variable Is Set or Not

To find out if a variable is set or not in a Bash shell script, you can use the -v option of the test command, also known as the [ command.

Here's an example of how you can use test to check if a variable is set:

if test -v myvar; then
  echo "myvar is set"
else
  echo "myvar is not set"
fi
Source:‮al.www‬utturi.com

This script will print "myvar is set" if the variable myvar is set, and "myvar is not set" if it is not set.

You can also use the ${var+x} parameter expansion to check if a variable is set:

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

This script will also print "myvar is set" if the variable myvar is set, and "myvar is not set" if it is not set.

Keep in mind that a variable can be set, but have an empty value. To check if a variable is set and not empty, you can use the -n option of the test command or the -z parameter expansion:

if test -n "$myvar"; then
  echo "myvar is set and not empty"
else
  echo "myvar is either not set or empty"
fi
if [ -n "${myvar:-}" ]; then
  echo "myvar is set and not empty"
else
  echo "myvar is either not set or empty"
fi

For more information about the test command and its available options, you can consult the test man page or use the test --help command.

Created Time:2017-10-27 14:56:35  Author:lautturi