Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an environment variable exists and get its value? [duplicate]

Tags:

bash

shell

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?

like image 560
Nicolas El Khoury Avatar asked Sep 02 '16 15:09

Nicolas El Khoury


People also ask

How do I check if an environment variable is set?

In the command window that opens, enter echo %VARIABLE%. Replace VARIABLE with the name of the environment variable you set earlier. For example, to check if MARI_CACHE is set, enter echo %MARI_CACHE%. If the variable is set, its value is displayed in the command window.

How do I get values from environment variables?

To display the values of environment variables, use the printenv command. If you specify the Name parameter, the system only prints the value associated with the variable you requested.

How do I check environment variables in bash?

To find out if a bash variable is defined: Return true if a bash variable is unset or set to the empty string: if [ -z ${my_variable+x} ]; Also try: [ -z ${my_bash_var+y} ] && echo "\$my_bash_var not defined" Determine if a bash variable is set or not : [[ ! -z ${PURGEIMAGE+z} ]] && echo "Set" || echo "Not defined"


1 Answers

[ -z "${DEPLOY_ENV}" ] checks whether DEPLOY_ENV has length equal to zero. So you could run:

if [[ -z "${DEPLOY_ENV}" ]]; then   MY_SCRIPT_VARIABLE="Some default value because DEPLOY_ENV is undefined" else   MY_SCRIPT_VARIABLE="${DEPLOY_ENV}" fi  # or using a short-hand version  [[ -z "${DEPLOY_ENV}" ]] && MyVar='default' || MyVar="${DEPLOY_ENV}"  # or even shorter use  MyVar="${DEPLOY_ENV:-default_value}" 
like image 174
endurogizer Avatar answered Sep 23 '22 00:09

endurogizer