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?

I tried, for testing purposes tempV=$(printenv LANG) it did not print anything, despite the system having the value of LANG
– Nicolas El KhourySep 2 '16 at 15:58

Your statement doesn't "print" anything. It stores the value of the environment variable LANG into the shell variable tempV. As for the other suggestions in this thread: Note that with none of them, you can distinguish, whether you have an environment variable or a shell variable. If this distinction is really important, the solution suggested by @sjsam should be considered.
– user1934428Sep 3 '16 at 6:17

My script was not able to read the value of DEPLOY_ENV, In order to be sure that the environment variable exists in the system, I wrote printenv DEPLOY_ENV in the terminal, and the correct value was returned. However, the script was not able to fetch it.
– Nicolas El KhourySep 2 '16 at 16:08

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:

if [ -z "$a" ]
then
echo "not defined"
else
echo "defined"
fi

and then set a default value for undefined variables or do something else.

The -z checks for a zero-length (i.e. empty) string. See man 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.