Skip to content
KALANBLON
Show contents

Chapter 2 of 6 · 20 min

Functions and error handling

By the end of this chapter, you'll be able to

  • Understand exit codes and test them
  • Stop a script at the first problem with set -euo pipefail
  • Split a script into functions with arguments and a return value
  • Print error messages on standard error and clean up with trap

Exit codes

Each command returns an exit status: 0 if everything went well, another number (from 1 to 255) on error. The $? variable holds the code of the last command:

printf "Awa\nKofi\n" > names.txt
grep -q "Lina" names.txt || echo "Lina missing, code: $?"
grep -q "Awa" names.txt && echo "Awa found, code: $?"
Lina missing, code: 1
Awa found, code: 0

grep -q searches for text without printing anything: its exit code is enough to know whether it found it. The && and || operators use these codes: command1 && command2 runs the second only if the first succeeded, command1 || command2 only if it failed.

Strict mode

Three options, placed at the start of every script, change everything:

#!/usr/bin/env bash
set -euo pipefail
  • -e: stop the script as soon as a command fails;
  • -u: treat an undefined variable as an error (a typo in a variable name no longer goes unnoticed);
  • -o pipefail: in a pipe a | b, report failure if any command fails, not only the last one.

The introduction's clean-up script would have stopped dead at the failed cd, before the rm. Demonstration:

set -euo pipefail
echo "Starting clean-up"
cd /srv/dropbox/old
echo "This line is never run"

The cd fails, the script stops with a non-zero code, and the last line is never run.

With set -e, the script stops as soon as cd fails: the rm line is never reached.

Step 4 of 4
Text description of the animation
  1. The folder was renamed: cd fails with code 1.
  2. By default, Bash prints the error then moves to the next line, in the current folder.
  3. The dangerous command runs in a folder that was never intended.
  4. With set -e, the script stops as soon as cd fails: the rm line is never reached.

Functions

A function gives a name to a group of commands. Its arguments are called $1, $2… like a script's. Its variables are declared with local, so they do not overwrite those of the rest of the script. A function returns a result by printing it, and you capture it with $( ):

set -euo pipefail

human_size() {
  local bytes=$1
  if (( bytes >= 1048576 )); then
    echo "$((bytes / 1048576)) MB"
  elif (( bytes >= 1024 )); then
    echo "$((bytes / 1024)) KB"
  else
    echo "$bytes B"
  fi
}

for s in 512 20480 5242880; do
  echo "$s bytes = $(human_size "$s")"
done
512 bytes = 512 B
20480 bytes = 20 KB
5242880 bytes = 5 MB

(( ... )) evaluates a condition on numbers, with the usual operators (>=, <…). The return instruction, on the other hand, only returns an exit code (0 for true, anything else for false): it is for functions that answer yes or no.

Error messages and clean-up

Error messages go to standard error (>&2), not standard output: that way, ./script.sh > report.txt keeps the errors visible on screen. And trap runs a command when the script ends, even on an error, for example to delete temporary files:

set -euo pipefail

fail() {
  echo "ERROR: $*" >&2
  exit 1
}

tmpfile=$(mktemp)
trap 'rm -f "$tmpfile"' EXIT

echo "list of students" > "$tmpfile"
[[ -s $tmpfile ]] || fail "the temporary file is empty"
echo "Processing done, the temporary file will be deleted."
Processing done, the temporary file will be deleted.

$* joins all the function's arguments into a single text; [[ -s file ]] is true if the file exists and is not empty.

Mini-lab: exit codesTerminal simulator

Terminal

Click “Run”: the commands run in a fresh terminal, in your home folder /home/awa. Type “help” for the list of commands.

Teaching simulator: it reproduces the essential Linux commands in your browser, with nothing to install · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: a checking function

Write a check_folder function that receives a path, and that prints an error on standard error and returns code 1 if the folder does not exist or is not writable. Otherwise, it prints OK: path. Test it on dropbox (to create) and on missing.

Hint 1
[[ -d $1 && -w $1 ]] tests both conditions at once.
Hint 2
To test a function that can fail without stopping the script, call it in an if or followed by || echo ....
Show the solution and common mistakes
set -euo pipefail

check_folder() {
  local path=$1
  if [[ -d $path && -w $path ]]; then
    echo "OK: $path"
  else
    echo "ERROR: $path missing or not writable" >&2
    return 1
  fi
}

mkdir -p dropbox
check_folder dropbox
check_folder missing 2>/dev/null || echo "missing refused (code $?)"
OK: dropbox
missing refused (code 1)

2>/dev/null hides the error message here so the output stays readable; in a real script, you let it show.

Common mistakes:

  • Using exit 1 in the function instead of return 1: exit stops the whole script, whereas the caller may have wanted to react to the failure.
  • Forgetting local: the path variable would overwrite a variable with the same name elsewhere in the script.

Summary

  1. 1Each command returns an exit code: 0 on success, something else otherwise.
  2. 2set -euo pipefail stops the script at the first error, on an unknown variable or a failed pipe.
  3. 3A function takes its arguments in $1, $2…, declares its variables with local and returns a result by printing it.
  4. 4Errors go to standard error with >&2; trap ... EXIT cleans up at the end.
  5. 5set -e does not apply in a function tested by if, && or ||: check important steps explicitly.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.