0

In bash, I can make a test condition utilize && and/or || rather than an if/elif/else block.

When applicable, I use tend to use && and/or || rather than building out an if block. Are there any real-world advantages to one construct over the other?

Consider the following examples:

1)

[[ -f /shared_disk/backups/daily.tar.bz2 ]] && echo "the coast is clear" || echo "run the dump"

2)

if [[ -f /shared_disk/backups/daily.tar.bz2 ]]; then
    echo "the coast is clear"
else
    echo "run the dump"
fi
2

1 Answer 1

5

The two forms you present are not exactly equal.

In the form: A && B || C, C will be executed if either A or B evaluate as false.

For example:

$ true && true || echo C
$ true && false || echo C
C
$

This gives one real-world advantage of the if-then-else form over the A && B || C form and that is clarity. It is clearer what the if-then-else form is doing, but you need to understand the rules of evaluation to understand what the A && B || C form is doing.

However it can often be beneficial to use A && B or A || B. That is clearer and can be useful when simple commands are being run. Sometimes one line instead of three is clearer, particularly when you're trying to take in a large amount of code.

3
  • 4
    IMO the most confusing thing about using && || instead of if then else is that it can run both the then-like command and the else-like command (if the first command succeeds and the second fails). You don't really expect a echo command to fail, but it can happen, and it'll be really really confusing if it ever does. A proper if then else statement runs either the then command(s) or the else commands, never both. Sep 16, 2017 at 6:45
  • @GordonDavisson: Why don’t you post that as an answer? Sep 18, 2017 at 20:32
  • @Scott: I consider camh's answer entirely correct as it is, I'm just pointing out a particularly troubling consequence. Sep 18, 2017 at 21:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .