Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 937
MLSC Avatar asked Aug 20 '14 12:08

MLSC


3 Answers

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.

like image 143
fedorqui 'SO stop harming' Avatar answered Oct 14 '22 09:10

fedorqui 'SO stop harming'


Other possibilities:

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

if [ "${var1:-xxx}" != "string" ]; then ...
like image 36
ooga Avatar answered Oct 14 '22 08:10

ooga


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
like image 37
opalenzuela Avatar answered Oct 14 '22 09:10

opalenzuela