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
MediumWrite a script that merges two name lists through a temp file and always removes it.
- Open
merge.sh. It already hasset -e. The two list files are its first and second arguments. - Create a temp file with
mktemp ./tmp.XXXXXXand keep its name intmp. - Right after, set a
traponEXITthat removes it withrm -f "$tmp". - Write both lists into the temp file with
cat. - Print the names sorted without repeats (
sort -u), thenTotal: Nwith how many names that is. - 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: 5Then 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
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