Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Linux by (9.5k points)

Below is the operation, I perform before I run the script: 

export DEPLOY_ENV=dev

When I run the script, I want to have a variable in the shell script which takes the default value when the environment variable is not present. If it’s present it has to store its value in a variable. Can anyone tell me how to do it? 

1 Answer

0 votes
by (19.7k points)

[ -z "${DEPLOY_ENV}" ] to check whether DEPLOY_ENV has a length equal to zero. See the below code: 

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}"

Interested in Linux? Check out this Linux Certification by Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 29, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked May 14, 2021 in Java by sheela_singh (9.5k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...