简体   繁体   中英

Checking if bash environment variables exist using a function

This may have been answered in other SO posts but I don't think I can find exactly what I am looking for.

I have a ( #!/usr/bin/env bash ) function that checks for the existence of an (environment) variable

checkForVariable() {
  if [[ -z $1 ]]; then
    echo "Error: Define $1 environment variable"
    exit 1
  fi
}

but in the error message I want it to tell me which env variable is missing.

If I call it using checkForVariable "${ENVIRONMENT_NAME}"

and if ENVIRONMENT_NAME is not set then obviously I will get Error: Define environment variable which is not useful.

How can I change my function so that I can pass checkForVariable a string and not a variable reference ie

checkForVariable "ENVIRONMENT_NAME"

I've tried eg. if [[ -z "\\$${1}" ]]; then if [[ -z "\\$${1}" ]]; then and if [[ -z "${$1}" ]]; then if [[ -z "${$1}" ]]; then but these don't work.

You can use the -v and negate it using the ! , and the test for the -x attribute instead of -z

checkForVariable() {
  local env_var=
  env_var=$(declare -p "$1")
  if !  [[ -v $1 && $env_var =~ ^declare\ -x ]]; then
    echo "Error: Define $1 environment variable"
    exit 1
  fi
}

Then you can do the testing inside the script.

checkForVariable ENVIRONMENT_NAME

This is according to help test.

help test | grep -- '^[[:space:]]*-v'

Output

-v VAR         True if the shell variable VAR is set.

And also the !

help test | grep -- '^[[:space:]]*!'

Output

! EXPR         True if expr is false.

Also for env variables as pointed out by chepner it is necessary to look for the -x attribute by testing the output of declare -p ENV_NAME

help declare | grep -- '^[[:space:]]*-x'

Output

-x        to make NAMEs export

Although the above works if you're testing the variable inside the script itself and not in interactive shell. Now if you want to do it in an interactive session then sourcing the file/script is needed for it to work.

Put this in your dotfiles / rcfiles , like in ~/.profile or ~/.bash_profile or ~/.bashrc

checkForVariable() {
  local env_var=
  env_var=$(declare -p "$1")
   if ! [[  -v $1 && $env_var =~ ^declare\ -x ]]; then
     echo "Error: Define $1 environment variable"
     return 1
   fi
 }

Just need to replace exit with return otherwise you're interactive session will exit immediately.

And then source that rcfile.

source ~/.profile 

Assuming ~/.profile is where that function is.

You can do your test during interactive session.

checkForVariable ENVIRONMENT_NAME

EDIT: As pointed out by chepner I have added the test for the -x attribute.

You may use this function:

checkForVariable() {
    if [[ -z ${!1+set} ]]; then
       echo "Error: Define $1 environment variable"
       exit 1
    fi
}

Then use it as:

checkForVariable ENVIRONMENT_NAME

Note that ${!1+set} dereference variable using given name in $1 to your function and :+set check is required to check env variables set to empty value.

Code Demo

Since you have env in your shebang you can do:

printenv | grep "^ENV_VARIABLE"

or you can use set:

set | grep -E "^ENV_VARIABLE=.+$"

And also a python oneliners:

python3 -c 'import os; import sys; print(bool(os.getenv(sys.argv[1])))'  HOME

You can chek printenv result in other way of course:

[ ! -z `printenv VAR` ] || echo "VAR not exists"

So in your function become

function checkEnv() { [ ! -z `printenv $1` ] || echo "$1 Error message.."; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM