Using Fewer if Statements
Problem
As a conscientious programmer, you took to heart what we described in the previous
recipe, Deciding Whether a Command Succeeds. You
applied the concept to your latest shell script, and now you find that
the shell script is unreadable, if with all those if statements checking the return code of
every command. Isn’t there an alternative?
Solution
Use the double-ampersand operator in bash to provide conditional execution:
$ cd mytmp && rm *
Discussion
Two commands separated by the double ampersands tells
bash to run the first command and then to run the
second command only if the first command succeeds (i.e., its exit status
is 0). This is very much like using
an if statement to check the exit status of the first command in order to
protect the running of the second command:
cd mytmp if (( $? == 0 )); then rm * ; fi
The double ampersand syntax is meant to be reminiscent of the
logical and operator in C Language. If you know
your logic (and your C) then you’ll recall that if you are evaluating
the logical expression A AND B, then
the entire expression can only be true if both (sub)expression A and (sub)expression B evaluate to true. If either one is false,
the whole expression is false. C Language makes use of this fact, and
when you code an expression like if (A
&& B) { … }, it will evaluate expression A first. If it is false, it won’t even bother
to evaluate B since the overall
outcome (false) has already been determined (by A being false).
So what does this ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access