This question already has an answer here:
- How to check if a variable is set in Bash? 31 answers
I am writing a shell script. In this shell script, I am have a variable that either takes a default value, or the value of an environment variable. However, the environment variable doesn't have to be present.
For instance, assume, before running the script, I perform the following operation:
export DEPLOY_ENV=dev
How do I tell the script to search for this environment variable, and store its value in a variable inside the script. Moreover, how do I tell the script that if this environment variable does not exist, store a default variable?
There is no difference between environment variables and variables in a script. Environment variables are just defined earlier, outside the script, before the script is called. From the script's point of view, a variable is a variable.
You can check if a variable is defined:
and then set a default value for undefined variables or do something else.
The
-z
checks for a zero-length (i.e. empty) string. Seeman bash
and look for the CONDITIONAL EXPRESSIONS section.You can also use
set -u
at the beginning of your script to make it fail once it encounters an undefined variable, if you want to avoid having an undefined variable breaking things in creative ways.If you don't care about the difference between an unset variable or a variable with an empty value, you can use the default-value parameter expansion:
If you do care about the difference, drop the colon
You can also use the
-v
operator to explicitly test if a parameter is set.All the answers worked. However, I had to add the variables that I needed to get to the sudoers files as follows:
You could just use parameter expansion:
So try this:
There's also the ${parameter-word} form, which substitutes the default value only when parameter is unset (but not when it's null).
To demonstrate the difference between the two:
[ -z "${DEPLOY_ENV}" ]
checks whetherDEPLOY_ENV
has length equal to zero. So you could run: