Linux, terminal and Git

Stage 7 · Lesson 2 of 8

Failing safely: exit codes and set -euo pipefail

Shell scripts and automation

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

Practise

Keep handy

  • Paste or run a script to catch quoting and error-handling bugs before they bite

  • Check what each part of an unfamiliar command does before you put it in a script

Also worth your time

Mark this stage as not done?