3

I'm trying to write a script which does something if a particular string is not present in a file.

I know that in order to check if string is available, we can do something like:

if grep -qi "sms" $FILE; then

But how do I combine a ! operator with a shell command?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
drunkenfist
  • 2,958
  • 12
  • 39
  • 73

2 Answers2

2

Just add it in front of your condition to make it evaluate on the contrary:

if ! grep -qi "sms" $FILE; then echo "yes"; fi
   ^

Test

$ cat a
hello
bye
$ if ! grep -qi "sms" a; then echo "sms not found"; fi
sms not found
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • @fedorqui Thanks. It works. I was trying !grep earlier. Apparently I have to leave a space between ! and grep. – drunkenfist Nov 19 '14 at 18:08
  • Nice to read that! Note that `!` is a keyword itself, so to make it work you need to make it be differentiated by the other keywords in action. That is, it needs a space around. – fedorqui Nov 20 '14 at 09:27
0

The ! makes "success" to become "failure" and vice versa from shell points of view. In shell you can also use && (logical and operation), || (logical or operation) and group expressions using curly braces { ... }. For example:

{ grep root /etc/passwd && ! grep user /etc/passwd; } && echo ok || echo not ok

Remember to put ; before }. See man sh for more details.

Note that above is a plain shell expression with if-else-like logic. If you want to use test command or [ or [[ then you can also use other type of grouping, boolean arithmetics and other functions. See man test.

Michał Šrajer
  • 30,364
  • 7
  • 62
  • 85