Skip to content

Instantly share code, notes, and snippets.

@pdkl95
Created July 7, 2019 18:09
Show Gist options
  • Save pdkl95/61fc242e7961cc2584a787ed1760c859 to your computer and use it in GitHub Desktop.
Save pdkl95/61fc242e7961cc2584a787ed1760c859 to your computer and use it in GitHub Desktop.
Using the "trap" shell builtin to cleanup a tempfile safely duiring errors.
#!/bin/bash
#####################################################
# An example of using a trap to cleanup a temporary #
# even during errors or early script exit. #
#####################################################
# an easy way to observe the tempfile:
# watch "command ls -l -tc --reverse /tmp | tail"
declare sim_pipeerr=false
declare sim_earlyexit=false
declare -i do_something_delay=3
while true ; do
case "$1" in
-p) sim_pipeerr=true ; shift ;;
-e) sim_earlyexit=true ; shift ;;
-d) do_something_delay=$2 ; shift 2 ;;
-h | --help) echo "Usage: $0 [-p] [-e]" ; exit 0 ;;
--) shift ; break ;;
-*) echo "bad opt: $1" ; exit 1 ;;
*) break ;;
esac
done
create_tmpfile() {
mktemp --tmpdir="${TMPDIR:-/tmp}" --suffix=".tmp" "$(basename "$0")"-XXXXXX
}
do_something() {
echo "Doing something with: '$1'"
if [[ -n "$do_something_delay" ]] ; then
echo "Sleeping for $do_something_delay ..."
sleep $do_something_delay
fi
if $sim_pipeerr ; then
echo "Ooops, pipeline error in do_something!"
: | false
fi
if $sim_earlyexit ; then
echo "Oops, do_something called exit early!"
exit 1
fi
}
work_with_temp_file() {
local tmpfile="$(create_tmpfile)"
trap "rm -f '${tmpfile}'" RETURN EXIT
# use $tmpfile
do_something "${tmpfile}"
# don't need to remember to rm $tmpfile at each repossible return point
# don't need to worry about do_something failing or exiting early
}
work_with_temp_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment