Stage 7 · Lesson 2 of 8
Failing safely: exit codes and set -euo pipefail
Every command finishes with an , a number that reports how it went. 0 means success and anything else means failure. $? holds the exit code of the last command.
By default, carries on after a command fails, which can be dangerous. Imagine a cd into a folder fails, and the next line is rm -rf *: it deletes files in the wrong folder. Starting a script with set -euo pipefail turns on .
-e stops on errors, -u treats unset variables as errors, and pipefail makes a pipeline fail when any step in it fails. Use || and && to handle failures you expect, and exit 1 with a clear message when something is wrong.
Common trapassuming a script that printed no error actually succeeded.
A question to check yourself, an AI practice session and 2 cheat sheet entries come when you add the roadmap to your account. Add it
Resources for this stage
Start with· follow one of these
- GuideFreeGreg's Wiki: BashGuide
Greg's Wiki (Wooledge) · Beginner
A careful, accurate Bash guide that teaches the habits that avoid most scripting bugs
- CourseFreeThe Missing Semester of Your CS Education
MIT · Beginner
The shell tools and scripting lecture, with exercises that build useful small scripts
Practise
Keep handy
Also worth your time
- roadmap.sh: Shell / BashGo deeper
The scripting side of the shell map: arrays, traps, parameter expansion and more