Skip to content

Scripts that decide: exit codes, test and if

AdvancedLesson 33 of 669 min

Every command answers with an exit code. Use $?, && and ||, test and if to write a bash script that checks before it acts, in a practice terminal.

A script that runs every night has nobody watching it. So before it does something, it should check that it can, and when something is wrong it should stop and say so. That starts with a number every command leaves behind.

Exit codes

Every command finishes with an exit code: 0 means it worked, anything else (usually 1) means it didn't. The shell keeps the last one in $?:

ls reports
echo $?
ls nowhere
echo $?

The second ls fails, so $? is 2. Many commands use different numbers for different problems, and man lists them.

&& and ||

&& runs the next command only if the first one worked. || runs it only if the first one failed:

mkdir -p backup && cp reports/summary.txt backup/
cat reports/missing.txt || echo "no such report"

test, also called [

test checks one thing and answers with nothing but its exit code. [ is the same command under another name, ending with ]. The spaces inside the brackets matter: [ -f file ], never [-f file].

TestTrue when
-f FILEthe file exists
-d DIRthe directory exists
-s FILEthe file exists and isn't empty
-z "$TEXT"the text is empty
A = Btwo pieces of text are the same
N -gt Mthe number N is greater than M (also -lt, -eq, -ne, -ge, -le)
[ -f reports/summary.txt ] && echo "the report is there"

if

if runs a command and picks a branch by its exit code: 0 runs the then part, anything else the else part. Any command works, not just [, so if grep -q ERROR app.log; then is fine too.

#!/bin/bash
if [ -f reports/summary.txt ]; then
  echo "ready"
else
  echo "missing summary" >&2
  exit 1
fi

>&2 sends the message to the error output, where problems belong. exit 1 ends the script with exit code 1, so whatever started it (you, another script, cron) can tell it failed. Without an exit, a script ends with the exit code of its last command.

Getting the script into a file

Open it in Vim with vim check-report.sh, or type it straight into the terminal with a here-document: cat > check-report.sh <<'EOF', then the lines, then a line with just EOF. The shell shows > while it waits for the rest. The quotes around EOF keep $ signs as they are.

Your turn

Write check-report.sh in your home directory. If reports/summary.txt exists, it prints ready and exits with 0; if not, it prints missing summary to the error output and exits with 1. Make it executable and run it. Then rename the report to reports/summary.old and run it again to see the other branch.

Next