-1

I wanted to check if the value of variable is empty in an if statement and take action based on the result from the same in a Bash script.

I am doing something like this:

if [ -z "${OriginSlotName-}" ] && [ -z "${TargetSlotName-}" ]; then

    echo "Value of both the slot are not given";

Although I pass the argument OriginSlotName and TargetSlotName as empty, this particular iteration is not executed rather it goes to the part of the bash script where its expecting both OriginSlotName and TargetSlotName.

Does anyone know, what might be wrong here? Or is there a better way to structure the script? As of now I have an if statement with four branches. The if statement looks something like the following:

If (OriginSlotName & OriginSlotName != Empty)
    Do something

else if (OriginSlotName = Empty & OriginSlotName != Empty )
    Do something

else if (OriginSlotName != Empty & OriginSlotName = Empty )
    Do something
else
    Do something (Both OriginSlotName & OriginSlotName = Empty )

Is there a better and more efficient way to perform these checks and take relevant action based on the result, apart from using if?

Spaniard89
  • 2,359
  • 4
  • 34
  • 55

3 Answers3

0

You can write your condition like this :

if [[ -z "${OriginSlotName}" &&  -z "${TargetSlotName}" ]]; then
    echo "Value of both the slot are not given";
fi

It will only validate this condition if both $OriginSlotName and $TargetSlotName are empty

Wee
  • 463
  • 3
  • 10
  • Thanks for the answer, just out of curiosity, what happens with my if statement. Logically, it should also work, but why is it not working? – Spaniard89 Aug 18 '17 at 10:14
  • Actually yes it should work. Maybe you have a strange bash version ? Can you find which one are you using ? – Wee Aug 18 '17 at 12:05
0

Your original if stmt generally works as well:

OriginSlotName=""
TargetSlotName=""

if [ -z "${OriginSlotName}" ]  && [ -z "${TargetSlotName}" ]; then
    echo "Value of both the slot are not given";
fi

echo "${TargetSlotName}"
echo "${OriginSlotName}"

When you run it, output (with GNU bash, Version 4.3.11(1)-release (x86_64-pc-linux-gnu) is:

Value of both the slot are not given

followed by two empty lines.

I think the pending hyphen "-" of the variables in your code is the root of your problem.

Würgspaß
  • 4,660
  • 2
  • 25
  • 41
  • Unfortunately, its not working. With above method if both are empty, then none of the if condition is being called. – Spaniard89 Aug 18 '17 at 11:05
0

The problem was how the script was being called, initially I called the script with all the required argument without enclosing them in double quotes. When calling the script with arguments enclosed in double quotes, the variable got evaluated. I also had to modify the script and use ecerulm answer from this post here: How to check if a variable is set in Bash?

Basically I also had to check for unset or empty when in a script with set -u defined.

Spaniard89
  • 2,359
  • 4
  • 34
  • 55