Dropping temporary files without cleaning them up is a little untidy; at the end of a script where temporary files are used, we should have a safe rm command to remove them afterward:
#!/bin/bash
# Code setting and using tempdir goes here, and then ...
# Remove the directory
if [[ -n $tempdir ]] ; then rm -- "$tempdir"/myscript-timestamp rmdir -- "$tempdir" fi
Notice that we're careful to check that tempdir actually has a value, using the -n test before we run this code, even if we don't think anything might have changed it; otherwise we'd be running rm -- /myscript-timestamp.
Notice also that we're carefully removing only the files we know we've created, rather than just specifying "$tempdir"/*. An empty value for the tempdir variable in such a case could have terrible consequences!
The preceding code is a good start for the ending of a script – but what about cases where a script is interrupted? Ideally, we'd delete the files even if someone pressed Ctrl + C to interrupt the script before it was finished.
Bash provides an EXIT trap for this purpose; we can define a command that should be run whenever the script exits, if it can possibly run it. The very start of our Bash script might look like this:
cleanup() {
if [[ -n $tempdir ]] ; then
rm -f -- "$tempdir"/myscript-timestamp
rmdir -f -- "$tempdir"
fi
}
trap cleanup EXIT
tempdir=$(mktemp -d) || exit
The cleanup function is run whenever the Bash script exits, and hasn't been sent the SIGKILL or kill -9 signal. If the tempdir variable is set, it tries to clear away a temporary file in it, and then remove the temporary directory itself. Notice that we set up the hook first, before the temporary directory is even created, to get it in place as soon as possible.