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"
fiWhen app.log has no ERROR, grep fails, if skips its block, and the script carries on.
Challenge
MediumMake a page publishing script stop when something goes wrong.
- Open
publish.sh. It copies the page named in its first argument intosite/, notes drafts and counts theTODOlines. - Add
set -eon its own line right after the comment, so a missing page stops the script with thecperror and code 1. grep -cexits with code 1 when it counts 0 lines, which would now stop the script. Add|| trueinside the$(...)on thetodos=line, so a page without TODOs prints(TODOs: 0).- Keep the
if grep -q DRAFTblock 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 directoryTry it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground