0

I'm writing a bash script where i need to combine two conditions with && operator

var1=value
var2=1

if [-z $var1 ] && [$var2=="1"]; then
   do something
else
   do something else
fi

but it always executes the else part.

My research

  1. google gave me bash conditions like this but its not working for me.
if [condition1] && [condition2]; then
 do something
fi
  1. Another method i tried is this but it still completely ignored the true part
if [[-z $var1 ]] && [$var2=="1"]; then
   do something
else
   do something else
fi
  1. Tried with -a operator like this
if [-z $var1  -a $var2=="1" ]; then
  1. tried nested if
if [-z $var1 ]; then
    if [$var2=="1"]; then
      do something
    fi
else
      do something else
fi

So i know i am doing something wrong but my goal is i want to check for any value in $var1 and also want $var2 condition to be true and execute the true part.

UPDATE

i tried this

#! /bin/bash 
set -o nounset
#set -o errexit
set -o pipefail
set -o xtrace
var1=pop
var2=1

if test -z "$var1" && test "$var2" -eq 1; then
    echo Y1
fi

if [ -z "$var1" ] && [ "$var2" -eq 1 ]; then
    echo Y2
fi

and this is the output

root@c847b6423295:/# ./test.sh 
+ var1=pop
+ var2=1
+ test -z pop
+ '[' -z pop ']'
root@c847b6423295:/# 

What am i doing wrong ?

1 Answers1

0

You want to encode "$var1 is not empty and $var2 is equal to 1", you can do:

if test -z "$var1" && test "$var2" -eq 1; then
    echo Y
fi

which is equivalent to:

if [ -z "$var1" ] && [ "$var2" -eq 1 ]; then
    echo Y
fi

If you want to compare strings, use a single equals sign:

if test "aaa" = "aaa"; then
    echo Y
fi
Nick Bull
  • 8,365
  • 5
  • 22
  • 43