Checking for environment variables
TL;DR Use this:
#!/bin/bash
if [[ ! -v MY_VAR ]]; then
echo "MY_VAR is not set"
elif [[ -z ${MY_VAR} ]]; then
echo "MY_VAR is set to an empty string"
else
echo "MY_VAR is set to ${MY_VAR}"
fi
Detecting Variables and their values
Bash is used for a lot of shell programming. It is one of the common shells out in the world, similar to sh, and others. Rather different than DOS though.
When writing a script a common need is to check if an environment variable exists, if it exists, is it set to a value or empty, and if it is set to a value, is that value what it is expected to be.
Checking to see if a string is not null -n
The comparison operator -n
is like saying "is not null"
#!/bin/bash
my_string_variable=""
if [[ -n $my_string_variable ]]; then
echo "The variable is not null and is set to : $my_string_variable"
else
echo "The variable is null"
fi
Checking to see if a string is null -z
The comparison operator -z
is like saying "Is Null" or "Is String Zero Length (a null string is zero length)"
#!/bin/bash
my_string_variable=""
if [[ -z $my_string_variable ]]; then
echo "The variable is null"
else
echo "The variable is not null and is set to : $my_string_variable"
fi
Checking if an environment variable is set to something
The -n
and -z
operators can both be used for checking an environment variable. However, they can't tell if a variable is not set, or if it is just an empty string.
#!/bin/bash
if [[ -n $MY_VAR ]]; then
echo "MY_VAR is set to $MY_VAR"
else
echo "MY_VAR is not set or set to an empty string"
fi
if [[ -z $MY_VAR ]]; then
echo "MY_VAR is not set or set to an empty string"
else
echo "MY_VAR is set to $MY_VAR"
fi
results in:
Variable not set == not set or empty string.
$ env ./test_string.sh
MY_VAR is not set or set to an empty string
MY_VAR is not set or set to an empty string
Variable is set, but set to empty string == "not set or set to empty string"
$ env MY_VAR= ./test_string.sh
MY_VAR is not set or set to an empty string
MY_VAR is not set or set to an empty string
Variable is set to 'SOMETHING' is detected
$ env MY_VAR=SOMETHING ./test_string.sh
MY_VAR is set to SOMETHING
MY_VAR is set to SOMETHING
Checking in an environment variable is set.
The -v
operator will check for a "is variable set" case. Putting it together results in this:
#!/bin/bash
if [[ ! -v MY_VAR ]]; then
echo "MY_VAR is not set"
elif [[ -z ${MY_VAR} ]]; then
echo "MY_VAR is set to an empty string"
else
echo "MY_VAR is set to ${MY_VAR}"
fi
Which, when tested results in this:
Variable is not set is detected
$ env ./test_string.sh
MY_VAR is not set
Variable is set to empty string is detected
$ env MY_VAR= ./test_string.sh
MY_VAR is set to an empty string
Variable is set to 'SOMETHING' is detected
$ env MY_VAR=SOMETHING ./test_string.sh
MY_VAR is set to SOMETHING