How do I write a script that cleans up its temp files even on errors?

Quick Linux Tip #20:

Try: TMPFILE=$(mktemp) && trap 'rm -f "$TMPFILE"' EXIT INT TERM

Info: mktemp creates a secure, unique file; trap catches signals like exit or Ctrl+C to guarantee cleanup.

Examples:

  • $ TMPDIR=$(mktemp -d)  # Secure temp directory
  • $ trap 'rm -rf "$TMPDIR"' EXIT
  • $ mktemp -t script-XXXXXX.log  # Custom prefix

Note: Prevents dangling files during unexpected script crashes. Permissions default to 600 (owner-only), preventing local information leaks.




LinuxTeck.com
linuxteck@ubuntu:~$ TMPFILE=$(mktemp)

linuxteck@ubuntu:~$ echo $TMPFILE
/tmp/tmp.A3B5c7D9

linuxteck@ubuntu:~$ trap 'rm -f "$TMPFILE"' EXIT INT TERM

linuxteck@ubuntu:~$ ls -la $TMPFILE
-rw------- 1 linuxteck linuxteck 0 Jun 26 15:34 /tmp/tmp.A3B5c7D9
linuxteck@ubuntu:~$

PREVIOUS ARTICLE Quick Linux Tip #19: How do I extract just the source IPs from active connections? NEXT ARTICLE Quick Linux Tip #21: I can't unmount a disk because something's using it. How do I find what?
About John Britto

John Britto Founder & Chief-Editor @LinuxTeck. A Computer Geek and Linux Intellectual having more than 20+ years of experience in Linux and Open Source technologies.

View all posts by John Britto →

Leave a Reply

Your email address will not be published.