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.
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.
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!?!
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"
if (grep -Fxq "abc" file1 && grep -Fxq "def" file2);
then
echo ""
else
echo "failed"
fi