How to Create Temporary Files in Bash: mktemp and trap
mktemp command
- The generated temp file name is random and readable/writable only by the user.
- To ensure creation succeeds, append OR (
||) aftermktempto exit on failure. - To delete temp files on script exit, use
trapto register cleanup.
#!/bin/bash
trap 'rm -f "$TMPFILE"' EXIT
TMPFILE=$(mktemp) || exit 1
echo "Our temp file is $TMPFILE"
mktemp options
-dcreates a temporary directory.-pspecifies the directory for temp files. Default is$TMPDIR. If not set,/tmpis used.-tspecifies a filename template. The template must end with at least three consecutiveXcharacters for randomness; sixXare recommended. The default template istmp.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.
