Skip to content

Instantly share code, notes, and snippets.

@dave-burke
Created June 3, 2016 14:48
Show Gist options
  • Save dave-burke/e4ef095e59f5d5480ad96cf165bf6dd5 to your computer and use it in GitHub Desktop.
Save dave-burke/e4ef095e59f5d5480ad96cf165bf6dd5 to your computer and use it in GitHub Desktop.
Bash script demonstrating how to handle signals and clean up after yourself when the script is ended unexpectedly.
#!/bin/bash
temp_dir="/tmp"
if [ -d "${TEMP}" ]; then
temp_dir="${TEMP}"
fi
this_file="$(basename ${0})"
temp_file="${temp_dir}/${this_file%.*}.$$.$RANDOM"
function cleanup {
rm --verbose "${temp_file}"
exit
}
function handle_hup {
echo "Hup hup hup!"
echo "(Received SIGHUP -- Terminal window closed.)"
cleanup
}
function handle_int {
echo "Kock kock."
echo "Who's there?"
echo "Interupting cow."
echo "Interupting co--"
echo "MOO!"
echo "(Received SIGINT -- ctrl-c)"
cleanup
}
function handle_term {
echo "I'll be back."
echo "(Received SIGTERM -- kill command)"
cleanup
}
trap handle_hup SIGHUP
trap handle_int SIGINT
trap handle_term SIGTERM
touch ${temp_file}
while true; do
clear
echo "The time is $(date)"
echo "My pid is $$"
echo "I created a file at ${temp_file}, but I will clean it up when you give the signal."
sleep 5
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment