NASutils Knowledge BaseUnofficialPolski

Bash · lesson 21 of 30 · Files and errorsClean up at the end

mktemp -d makes a work folder and trap EXIT removes it, also after an error.

Programming on the NAS › Bash in 30 lessons

21-trap.sh Download 21-trap.sh

#!/usr/app/TurboShell/bin/bash
set -euo pipefail
# A work folder that is gone at the end, also after an error
work=$(mktemp -d "$PWD/work.XXXXXX")
trap 'rm -rf "$work"; echo "cleaned up"' EXIT

sort -u words.txt >"$work/sorted.txt"
echo "$(wc -l <"$work/sorted.txt") lines in the work folder"

Terminal

$ bash 21-trap.sh
3 lines in the work folder
cleaned up
$ ls -d work.* 2>/dev/null || echo "no work folder is left"
no work folder is left

Exercise

Press Ctrl+C in a longer script and check the folder is gone.