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
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"
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With