AnyCompiler

Error Handling, and a Closing Look

By default Bash keeps running after a command fails, as the variables lesson's "command not found" line demonstrated. set -e changes that: it makes the whole script exit immediately the moment any command returns a nonzero exit status.

set -e
echo "before"
false
echo "after (should not print)"
Output
before

set -u adds a second layer of strictness: referencing a variable that was never set becomes a fatal error too, instead of silently expanding to an empty string. This is genuinely what the real run reports:

set -u
echo "$undefined_var"
Output
script.sh: line 2: undefined_var: unbound variable

&& runs its right side only if the left side succeeded (exit code 0), and || runs its right side only if the left side failed — both short-circuit on exit codes directly, without needing an if statement at all.

true && echo "yes1"
false || echo "yes2"
Output
yes1
yes2

That's the foundation of Bash: no static types at all, with every variable a string unless an arithmetic context says otherwise; exit codes (0-255, 0 for success) as the result of every command, including a function's own return; command substitution as the way to turn a command's printed output into an actual value; parameter expansion as the string-manipulation toolkit in place of methods; pipes and redirection as core syntax for composing commands; and set -e/set -u as the opt-in strictness that makes mistakes fail loudly instead of silently. From here, the best next step is practice — automate one small, real task you'd otherwise do by hand, and lean on set -e and set -u from the start so mistakes surface immediately instead of hiding.

Practice exercise

Using &&, print "ready" only if the true command succeeds. Using ||, print "fallback" only if the false command fails.

← Case StatementsMore lessons coming soon