Bash conditional on command exit code
bash
Solution
Yes there is:
if grep --quiet .....
then
# If grep finds something
fi
or if the grep fails
if ! grep --quiet .....
then
# If grep doesn't find something
fi
Problem
In bash, I want to say "if a file doesn't contain XYZ, then" do a bunch of things. The most natural way to transpose this into code is something like: ``` if [ ! grep --quiet XYZ "$MyFile" ] ; then ... do things ... fi ``` But of course, that's not valid Bash syntax. I could use backticks, but then I'll be testing the output of the file. The two alternatives I can think of are: ``` grep --quiet XYZ "$MyFile" if [ $? -ne 0 ]; then ... do things ... fi ``` And ``` grep --quiet XYZ "$MyFile" || ( ... do things ... ) ``` I kind of prefer the second one, it's more Lispy and the || for control flow isn't that uncommon in scripting languages. I can see arguments for the first one too, although when the person reads the first line, they don't know why you're executing grep, it looks like you're executing it for it's main effect, rather than just to control a branch in script. Is there a third, more direct way which uses an `if` statement and has the `grep` in the condition?