>_ IzzyLab

Hands-on task

This task is step 12 of the course “Processes and signals”

trap: cleanup on exit

medium~7 min

Write a script /root/cleanup.sh that creates a lock file /root/tmp.lock, and on termination (the EXIT signal) removes it via trap. After running the script, no lock file should remain.

What you'll practise:
  • trap
  • EXIT signal
  • bash script
  • resource cleanup
  • lock file

Topic breakdown

trap 'command' SIGNAL installs a handler that fires when the signal is received. The pseudo-signal EXIT is special: it runs on any termination of the script — normal or due to an error — which makes it the ideal place for guaranteed cleanup of temporary resources. The key point is to install the trap before creating the resource, otherwise in the gap between creation and installation the handler won't help; and the removal itself is best done "softly" (rm -f), so it doesn't fail if the file is already gone.

What's checked

  1. the script has a trap on EXIT
  2. lock file removed after running
  3. the script creates the lock, and the trap removes it on exit

What it looks like