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.

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

3 Answers 3

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!?!

Sign up to request clarification or add additional context in comments.

1 Comment

What specifically does not work? Are you using bash ({ ... } construct is bash extension)?
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" 

Comments

2
if (grep -Fxq "abc" file1 && grep -Fxq "def" file2);
then
  echo ""
else
  echo "failed"
fi

2 Comments

exactly the same, I've written, +1
@chepner I used OP's code snippet to answer his question. Corrected it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.