Skip to content

Instantly share code, notes, and snippets.

@DerBunman
Last active June 10, 2019 15:43
Show Gist options
  • Save DerBunman/1b0d6d163008faebddfb0caf6b235c30 to your computer and use it in GitHub Desktop.
Save DerBunman/1b0d6d163008faebddfb0caf6b235c30 to your computer and use it in GitHub Desktop.
zsh: cleanup mktemp files on script exit/term
#!/usr/bin/env zsh
MKTEMP_BIN="$(which mktemp)"
tempfiles="$(mktemp)"
function mktemp(){
local filename="$($MKTEMP_BIN "${@}")"
echo "$filename" >> "$tempfiles"
echo "$filename"
}
function on_exit() {
test -f "$tempfiles" && {
#echo "starting on_exit cleanup"
while read file; do
#echo removing $file
test -f "$file" && rm -f "$file"
done < "$tempfiles"
#echo "removing $tempfiles (tempfile list)"
test -f "$tempfiles" && rm -f "$tempfiles"
}
}
trap on_exit EXIT INT TERM
# now when we use mktemp in this script, it will go thru the function mktemp
# and then on EXIT/INT/TERM the trap on_exit will delete these files
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment