Trap Signal Handler in Shell

Level 4131 keystrokes

trap runs the cleanup function when the script exits or receives INT (Ctrl+C) or TERM, so temporary files are always removed. The PID in the output varies.

Shell code

# Cleanup function called by the trap
1cleanup() {
2 echo "Cleaning up temp files..."
# Delete all files matching /tmp/myapp_*
3 rm -f /tmp/myapp_*
# Exit with status 0, so an interrupted run also ends here
4 exit 0
5}
# Call cleanup on normal exit, Ctrl+C (INT) or kill (TERM)
6trap cleanup EXIT INT TERM
# $$ is this shell's PID; when the script ends, the EXIT trap runs cleanup
7echo "Script running (PID: $$)"

Output

Script running (PID: 12345)
Cleaning up temp files...
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 4
  • .× 3
  • (× 2
  • )× 2
  • /× 2
  • $× 2
  • _× 1
  • -× 1
  • :× 1
  • {× 1

More Shell examples at level 4

← Shell typing practice