How to check if multiple variables are defined or not in bash

前端 未结 3 1200
情话喂你
情话喂你 2021-01-31 08:19

I want to check, if multiple variable are set or not, if set then only execute the script code, otherwise exit.

something like:

if [ ! $DB==\"\" &&a         


        
3条回答
  •  暖寄归人
    2021-01-31 08:53

    You can use -z to test whether a variable is unset or empty:

    if [[ -z $DB || -z $HOST || -z $DATE ]]; then
      echo 'one or more variables are undefined'
      exit 1
    fi
    
    echo "You are good to go"
    

    As you have used the bash tag, I've used an extended test [[, which means that I don't need to use quotes around my variables. I'm assuming that you need all three variables to be defined in order to continue. The exit in the if branch means that the else is superfluous.

    The standard way to do it in any POSIX-compliant shell would be like this:

    if [ -z "$DB" ] || [ -z "$HOST" ] || [ -z "$DATE" ]; then
      echo 'one or more variables are undefined'        
      exit 1
    fi
    

    The important differences here are that each variable check goes inside a separate test and that double quotes are used around each parameter expansion.

提交回复
热议问题