MLSC
MLSC

Reputation: 5972

check two conditions in if statement in bash

I have problem in writing if statement

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

I want to write if statement that check:

If var1 is not null AND if string(could be hello word) is not in var1 then do stuff.

How can I do that?

Upvotes: 5

Views: 7016

Answers (3)

ooga
ooga

Reputation: 15501

Other possibilities:

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

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

Upvotes: 4

fedorqui
fedorqui

Reputation: 289505

Just use something like this:

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

See an 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 indicated in String contains in bash.

Upvotes: 7

opalenzuela
opalenzuela

Reputation: 3171

You should rephrase the condition like this:

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

or the equivalent:

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

Upvotes: 1

Related Questions