mktemp command

  • The generated temp file name is random and readable/writable only by the user.
  • To ensure creation succeeds, append OR (||) after mktemp to exit on failure.
  • To delete temp files on script exit, use trap to register cleanup.
#!/bin/bash

trap 'rm -f "$TMPFILE"' EXIT

TMPFILE=$(mktemp) || exit 1
echo "Our temp file is $TMPFILE"
mktemp options
  • -d creates a temporary directory.
  • -p specifies the directory for temp files. Default is $TMPDIR. If not set, /tmp is used.
  • -t specifies a filename template. The template must end with at least three consecutive X characters for randomness; six X are recommended. The default template is tmp. followed by ten random characters.

trap usage

The trap command handles system signals in Bash scripts.

The most common signal is SIGINT (interrupt), generated by Ctrl + C. The -l option lists all signals.

$ trap -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT
 4) SIGILL   5) SIGTRAP  6) SIGABRT
 ... ...

The trap format is:

$ trap [action] [signal]

Action is a Bash command.

Signals:

  • HUP: number 1, the script is detached from its terminal.
  • INT: number 2, user pressed Ctrl + C to interrupt the script.
  • QUIT: number 3, user pressed Ctrl + backslash to quit the script.
  • KILL: number 9, kill the process.
  • TERM: number 15, default signal sent by kill.
  • EXIT: number 0, not a system signal; a Bash-specific signal triggered on script exit.

Note: trap must be at the beginning of the script. Otherwise, any command above it that exits will not be captured.