5

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?

MLSC
  • 5,872
  • 8
  • 55
  • 89

3 Answers3

7

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.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
4

Other possibilities:

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

if [ "${var1:-xxx}" != "string" ]; then ...
ooga
  • 15,423
  • 2
  • 20
  • 21
  • Thank you... I was searching aboat `-a` and `-o` in if statements as well – MLSC Aug 20 '14 at 12:59
  • 1
    You can ignore `-a` and `-o` as Boolean operators. Even the POSIX standard recommends using `[ ... ] && [ ... ]` in place of `[ ... -a ...]` (and similarly for `||` in place of `-o`). – chepner Aug 20 '14 at 13:16
  • @chepner Interesting. Thanks for the info. – ooga Aug 20 '14 at 18:44
  • @chepner Thank you..So it is better to use `&&` and `||` rather than `-a` and `-o`... – MLSC Aug 21 '14 at 06:51
  • 1
    @MortezaLSC yes, see [this good explanation](http://stackoverflow.com/questions/16396146/using-and-operator-in-if-statement-bash-script#comment23507000_16396181): "Note that POSIX recommends the use of `&&` and `||` with the single bracket notation over `-a` and `-o`". – fedorqui Aug 21 '14 at 09:41
1

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
opalenzuela
  • 3,139
  • 21
  • 41