Check two conditions in if statement in bash

I have a problem in writing if the operator

var1=`COMMAND | grep <Something>`
if [ -n "$var1" ] && if [[ "$var1" != string ]]; then
    .
    .
    .
fi

      

I want to write an if statement that checks:

If var1 is not null AND if the string (maybe hello

word) is not in var1 then do stuff.

How can i do this?

+3


source to share


3 answers


Just use something like this:

if [ -n "$var1" ] && [[ ! $var1 == *string* ]]; then
...
fi

      

See example:



$ v="hello"
$ if [ -n "$v" ] && [[ $v == *el* ]] ; then echo "yes"; fi
yes
$ if [ -n "$v" ] && [[ ! $v == *ba* ]] ; then echo "yes"; fi
yes

      

The second condition is a variation of what is specified in String contains in bash .

+4


source


Other possibilities:



if [ -n "$var1" -a "$var1" != string ]; then ...

if [ "${var1:-xxx}" != "string" ]; then ...

      

+4


source


You should rephrase the condition as follows:

var1=`COMMAND | grep <Something>`
if [ -n "$var1" ] && [[ "$var1" != "string" ]]; then
.
.
.
fi

      

or equivalent:

if test -n "$var1"  && test "$var1" != "string"
then
...
fi

      

+1


source







All Articles