Menu
CoddyTech

Stop On Errors

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 27 of 39.

By default a script keeps going after a command fails. set -e makes it stop at the first failing command and exit with that command's code.

#!/bin/bash
set -e
cp notes.txt backup/
echo "Backup done"

If notes.txt is missing, bash save.sh prints the cp error and exits with code 1, and Backup done never appears. Without set -e, it prints the error and then Backup done.

Some failures are expected. Adding || true turns a failure into success, so the script goes on. A command tested by if or while, or placed before && or ||, does not stop the script either.

rm old.txt 2>/dev/null || true
if grep -q ERROR app.log; then
  echo "Errors found"
fi

When app.log has no ERROR, grep fails, if skips its block, and the script carries on.

challenge icon

Challenge

Medium

Make a page publishing script stop when something goes wrong.

  1. Open publish.sh. It copies the page named in its first argument into site/, notes drafts and counts the TODO lines.
  2. Add set -e on its own line right after the comment, so a missing page stops the script with the cp error and code 1.
  3. grep -c exits with code 1 when it counts 0 lines, which would now stop the script. Add || true inside the $(...) on the todos= line, so a page without TODOs prints (TODOs: 0).
  4. Keep the if grep -q DRAFT block as it is, and save the file.

Try it: run bash publish.sh index.html. It prints:

Published index.html (TODOs: 1)

Then run bash publish.sh home.html, a page that does not exist. It prints only the error and exits with code 1:

cp: cannot stat 'home.html': No such file or directory

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground