#!/bin/sh # My current understanding about # how to clean up temp files in POSIX shell. # (NB: mktemp is reasonably portable… yet not POSIX) tmpfile=$(mktemp) echo "Creating temporary file ${tmpfile}…" >"$tmpfile" if test -f "$tmpfile"; then echo "… ok" else echo "… problem, stopping" exit 1 fi cleanup () { echo "removing $tmpfile" >&2 rm "$tmpfile" } # cleaning up when the script exits normally trap cleanup EXIT # cleaning up when the script receives a termination signal, # and killing itself with the same signal. # * HUP = hangup # * INT = user interrupt (^C) # * TERM = normal termination signal # Not included: # * QUIT, which is the user interrupt (^\) used for debugging, # so we want to keep the temp file # * PIPE (write on a pipe that no one reads) : I'm not sure # what to do yet # * others? # NB: it seems that this signal format is the only POSIX-compliant # one for both trap and kill for signal in HUP INT TERM; do trap "cleanup; trap - $signal; kill -s $signal $$" $signal done echo "Here are the traps that were set:" trap while :; do echo "coucou" | tee -a "$tmpfile" sleep 1 done echo "This will never get printed"