Skip to the workspace
Pebellslearn by building
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.

shell bash / &&, || and ! : Chaining on Success

Explore each scene at your own pace.

01 · The rule

The rule

&&, || and ! : Chaining on Success

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

Trace conditional command execution and identify when an apparent if/else chain differs.

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
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.