Free — no signup required

Conditional Execution: && and ||

2 min read

One-Liner Logic

You do not always need a full if/then/fi block to make decisions. The && and || operators let you chain commands based on exit codes in a single line. They work because every command produces an exit code, and these operators inspect that code before deciding whether to run the next command.

The AND Operator (&&): runs the second command only if the first command succeeds (exit code 0). Chaining a directory-creation step and a copy step this way means the copy simply never runs if the directory creation failed — no confusing "destination doesn't exist" error, because the dependent step was never reached.

The OR Operator (||): runs the second command only if the first command fails (exit code non-zero) — the natural way to express "do this, and if it fails, do this instead" as a single line.

Combining both into a command && echo success || echo failure pattern creates simple if-then-else logic in one line.

A subtle trap with &&/|| chains: the || part runs if anything before it failed, including the && success branch if it fails. For complex logic, use a proper if statement instead. The one-liner pattern above is fine when the success branch is a simple message, but produces unexpected results if the success branch itself can fail — a genuine follow-up action after the && should live inside an if/else block, where its own failure can't accidentally trigger the || branch meant for the original command.

This is one of 18 chapters

Every chapter is free — Kubernetes, Terraform, SRE, distributed systems, and more — with fast daily review built in.

Sign up free