Menu
CoddyTech

Cleaning Up With trap

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

A script often needs a scratch file. mktemp ./tmp.XXXXXX creates an empty file with a unique name, such as ./tmp.k3J9qa, and prints that name. The scratch file must go away when the script ends, even when it ends early.

#!/bin/bash
set -e
tmp=$(mktemp ./tmp.XXXXXX)
trap 'rm -f "$tmp"' EXIT
grep ERROR app.log > "$tmp"
wc -l < "$tmp"

trap 'command' EXIT runs the command whenever the script exits: after its last line, at an exit, or when set -e stops it. The single quotes delay $tmp until the trap runs.

When app.log has two ERROR lines, bash report.sh prints 2 and the trap removes the file. When it has none, grep fails and set -e stops the script, but the trap still runs, so ls shows no tmp. file afterwards. The trap keeps the script's exit code.

challenge icon

Challenge

Medium

Write a script that merges two name lists through a temp file and always removes it.

  1. Open merge.sh. It already has set -e. The two list files are its first and second arguments.
  2. Create a temp file with mktemp ./tmp.XXXXXX and keep its name in tmp.
  3. Right after, set a trap on EXIT that removes it with rm -f "$tmp".
  4. Write both lists into the temp file with cat.
  5. Print the names sorted without repeats (sort -u), then Total: N with how many names that is.
  6. Save the file. No tmp. file may be left behind, also when a list is missing.

Try it: run bash merge.sh monday.txt tuesday.txt. It prints:

Ana
Ben
Cara
Dev
Eli
Total: 5

Then run bash merge.sh monday.txt friday.txt. There is no friday.txt, so set -e stops the script after cat: friday.txt: No such file or directory, and ls shows no temp file.

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