A script that writes a temp file must delete it, also when it fails:
| Line | Does |
|---|---|
tmp=$(mktemp) | Makes a new, empty file in /tmp, like /tmp/tmp.Tt23j5nJw8, and gives its name |
dir=$(mktemp -d) | Makes a new, empty folder instead. Delete it with rm -rf "$dir" |
trap 'COMMANDS' EXIT | Runs COMMANDS when the script ends, however it ends: at the last line, at exit 1, or when set -e stops it |
learner@reef:~$ cat sales.sh
#!/bin/bash
# Usage: sales.sh LOG
set -e
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT ← right after mktemp
grep sale "$1" > "$tmp"
echo "sales: $(wc -l < "$tmp")"
learner@reef:~$ ./sales.sh ~/logs/register.log
sales: 2
learner@reef:~$ ./sales.sh ~/logs/oven.log
grep: /home/learner/logs/oven.log: No such file or directory
learner@reef:~$ ls /tmp
learner@reef:~$ ← nothing left behind~/price-update.sh NEW_LIST builds the new price list in a temp file. Every run that fails leaves that file in /tmp.
- Run
./price-update.sh ~/nope.txt, a list that does not exist, thenls /tmp. - In
nano ~/price-update.sh, add a trap that deletes the temp file. Run step 1 again:/tmpgets no new file. - Run it on the real list:
./price-update.sh ~/new-prices.txt.
The tests also make mv fail, so that set -e stops the script: /tmp must still be empty.
Objectives
- When it fails, it leaves
/tmpempty. - It still updates the prices.
- When
set -estops it, it leaves/tmpempty.