Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash conditional on command exit code

Tags:

bash

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?

like image 678
Martin C. Martin Avatar asked Aug 19 '13 16:08

Martin C. Martin


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

How do I exit bash code?

When a command terminates on a fatal signal whose number is N , Bash uses the value 128+ N as the exit status. If a command is not found, the child process created to execute it returns a status of 127. If a command is found but is not executable, the return status is 126.

How do I check exit status on last command?

To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.


2 Answers

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
like image 125
user000001 Avatar answered Sep 19 '22 17:09

user000001


You don't need the [ ] (test) to check the return value of a command. Just try:

if ! grep --quiet XYZ "$MyFile" ; then
like image 22
Costi Ciudatu Avatar answered Sep 21 '22 17:09

Costi Ciudatu