&&, || and ! : Chaining on Success
A full if block for "make the folder or give up" takes four lines. Bash has a shorter way to say "do this, and only if it worked, do that", using the exit statuses you already know.
The rule
&&continues after success;||steps in after failure.
mkdir -p "$dest" || exit 1 # stop if the folder cannot be made
tar -czf "$archive" "$src" && echo "Saved" # announce only real success
[[ -d "$src" ]] || { echo "No such folder" >&2; exit 1; }a && brunsbonly ifaexited with 0. The whole line fails if either fails.a || brunsbonly ifaexited with non-zero. It is the natural "or else" for guards.! aflips the status: success becomes 1, failure becomes 0.- Braces
{ ...; }group several commands into one, so a guard can print and exit. Note the spaces and the final;.
The same words combine tests inside [[ ]]:
if [[ -d "$src" && -r "$src" ]]; then ... # both must hold
if [[ "$mode" == daily || "$mode" == weekly ]]; then ... # either oneThe shortcut
Read && as "and then, if that worked" and || as "or else". Each operator looks only at the exit status of whatever ran last before it, whichever command that was.
That is the trap in the popular one-liner a && b || c. It is not if/else:
Run true
It succeeds, so
&&lets the next command run.
Drills
Answer fast — trust the rule.
What does false && echo A print?
The command false, then the OR operator, then echo B. What prints?
What does ! true; echo $? print?
In a && b followed by the OR operator and c, when does c run?
What does [[ -d /tmp && -w /tmp ]] test?
Remember
&&continues after success;||steps in after failure;!flips.- Each operator looks only at the status of whatever ran last before it.
- Trap:
a && b || cis not if/else; useifwhen both branches matter.
