Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

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=="" && $HOST=="" && $DATE==""  ]; then   echo "you did not set any variable"    exit 1; else   echo "You are good to go" fi       
like image 404
ramesh.mimit Avatar asked Mar 26 '15 12:03

ramesh.mimit


People also ask

How do you check if a variable is defined 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"

Can I use != In bash?

Linux Bash scripting language provides the not equal “-ne” operator in order to compare two values if they are not equal. The not equal operator generally used with the if or elif statements to check not equal and execute some commands.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


1 Answers

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.

like image 113
Tom Fenech Avatar answered Sep 24 '22 16:09

Tom Fenech