1

How do I do something like:

if !("abc" in file1 and "def" in file2)
then
  echo "Failed"
fi

I've already known how to check "abc" in file1: grep -Fxq "abc" file1, but I can't manage to get the if not (command1 and command2) part to work.

pckben
  • 867
  • 2
  • 9
  • 24
  • 1
    Use De-morgans law - http://en.wikipedia.org/wiki/De_Morgan's_laws - i.e. "not(A and B)" becomes "not A or not B" – Ed Heal Mar 14 '13 at 11:42
  • Thanks, the problem is I don't know how to write it using bash script... – pckben Mar 14 '13 at 11:48

3 Answers3

4

You got it almost right. Just add a space between the exclamation mark and the grep commands, and it would work:

if ! (grep -Fxq "abc" file1 && grep -Fxq "def" file2); then
     echo "Failed"
fi

Assuming bash, there is no need for extra else.

Note that using parenthesis runs the greps in a subshell environment, as a child shell process. You can easily avoid this by using curly braces (this thing is called group command):

if ! { grep -Fxq "abc" file1 && grep -Fxq "def" file2; }; then
     echo "Failed"
fi

Note that you need more spaces and an additional semicolon – isn't bash syntax just so funny!?!

FooF
  • 4,323
  • 2
  • 31
  • 47
  • What specifically does not work? Are you using `bash` (`{` ... `}` construct is `bash` extension)? – FooF Nov 07 '13 at 10:02
2

You could do:

$ grep -Fxq "abc" file1 && grep -Fxq "def" file2 || echo "Failed"

This uses the bash logical operators AND && and OR ||.

This can be split over multiple lines like:

$ grep -Fxq "abc" file1 && 
> grep -Fxq "def" file2 ||
> echo "Failed" 
chepner
  • 497,756
  • 71
  • 530
  • 681
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
2
if (grep -Fxq "abc" file1 && grep -Fxq "def" file2);
then
  echo ""
else
  echo "failed"
fi
nav_jan
  • 2,473
  • 4
  • 24
  • 42