Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Exit Codes and Conditionals  ›  Lesson

&&, || and ! : Chaining on Success

Logical 12 min&& runs the next command only if the previous one succeeded, || runs it only if the previous one failed, and ! inverts an exit status.

&&, || 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 && b runs b only if a exited with 0. The whole line fails if either fails.
  • a || b runs b only if a exited with non-zero. It is the natural "or else" for guards.
  • ! a flips 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 one

The 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:

true && false || echo CStep 1 of 4
  1. Run true

    It succeeds, so && lets the next command run.

Drills

Answer fast — trust the rule.

quick drill

What does false && echo A print?

quick drill

The command false, then the OR operator, then echo B. What prints?

quick drill

What does ! true; echo $? print?

quick drill

In a && b followed by the OR operator and c, when does c run?

quick drill

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 || c is not if/else; use if when both branches matter.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainShort guards

Rewrite two steps of backup.sh as one-liners: create the backups folder or stop the script if that fails, and print Saved only if tar succeeds. Then explain why cmd && echo ok || echo failed is not a true if/else.