>_ IzzyLab

Hands-on task

This task is step 21 of the course “Bash scripts: from a loop to a robust script”

A script with trap cleanup

medium~10 min

Write /usr/local/bin/worktmp that creates a temporary file, does something with it, and is guaranteed to delete it on exit — even if the script is interrupted. After running, no temporary files should remain. Do the cleanup with trap. The script is easiest to write in the Editor tab above the terminal: /usr/local/bin is open there next to /root.

What you'll practise:
  • trap
  • mktemp
  • signal handling
  • EXIT
  • resource cleanup

Topic breakdown

If you delete the temporary file simply as the script's last line, then on an error in the middle or an interruption (Ctrl-C) it's never reached and the junk remains. The reliable technique is trap: it hangs a handler command on a signal or pseudo-event, and it runs on any exit from the script. The key idea is to create the file safely with mktemp (a unique name) and, on the very next line, hang cleanup on the EXIT event, which fires on normal termination, on error, and by signal alike.

What's checked

  1. worktmp is executable
  2. temporary files removed from /tmp
  3. cleanup is hooked up through trap

What it looks like