command1 && command2 || command3
Only if command1
is successful (exits with exit code 0), will command2
get executed.
If command1
fails, then command3
will get executed.
If command1
is successful, and command2
fails, then also command3
will get executed.
This last example demonstrates the difference from a classic if
statement:
if command1; then command2; else command3; fi
With this if
statement, if command1
is successful, and command2
fails, command3
will not get executed, contrary to the ... && ... || ...
form.
Consider this:
ok() { echo $1; }
fail() { echo $1; return 1; }
echo case ok ok
ok 1 && ok 2 || ok 3
# -> outputs: 1 2
echo case ok fail
ok 1 && fail 2 || ok 3
# -> outputs: 1 2 3
echo case fail ok
fail 1 && ok 2 || ok 3
# -> outputs: 1 3
echo case fail fail
fail 1 && fail 2 || ok 3
# -> outputs: 1 3
echo case ok ok
if ok 1; then ok 2; else ok 3; fi
# -> outputs: 1 2
echo case ok fail
if ok 1; then fail 2; else ok 3; fi
# -> outputs: 1 2
echo case fail ok
if fail 1; then ok 2; else ok 3; fi
# -> outputs: 1 3
echo case fail fail
if fail 1; then fail 2; else ok 3; fi
# -> outputs: 1 3