Cleaning Up Temporary Files on Exit

Su Suriya Ravichandran Updated 06 Dec 2026
11 min read ·Lesson 124 of 205

Scripts create temporary files and directories all the time: a place to collect intermediate results, a scratch copy of a file being edited, a download that is checked before it is moved into place. Lesson 113 showed how to create them safely with mktemp. This lesson covers the other half: making sure they are removed again, no matter how the script ends. The tool for that is an EXIT trap (lesson 123), and most of the details are about using it correctly.

Why "rm at the End" Is Not Enough

The obvious approach removes the file on the last line:

tmp=$(mktemp)
echo "created $tmp"
ls /nonexistent > "$tmp" 2>&1 || exit 1
rm -f -- "$tmp"
created /tmp/tmp.fOPFLzFgRa

The script ended with status 1, and a check afterwards confirmed that /tmp/tmp.fOPFLzFgRa was still there. Every exit before the last line, every failure that stops a set -e script, and every Ctrl+C skips the rm. Run often enough, such a script fills /tmp with forgotten files, and if the files contain data (a database dump, a decrypted secret), leaving them behind is a security problem as well as clutter.

The Basic Pattern

Register the cleanup right after creating the file:

tmp=$(mktemp)
trap 'rm -f -- "$tmp"' EXIT
ls /nonexistent > "$tmp" 2>&1 || exit 1
echo "not reached"

The script still ended with status 1, but this time the file was gone. The EXIT trap runs on every normal way out: the end of the script, an exit anywhere, and a stop caused by set -e. In Bash it also runs when SIGINT or SIGTERM ends the script (lesson 123).

The parts of the trap command each have a purpose:

  • Single quotes delay the expansion of $tmp until the trap runs. The trap uses whatever value the variable has at exit time.
  • rm -f does not complain or fail if the file is already gone, for example because the script moved it to its final location.
  • -- ends the option list, so a path that begins with - cannot be mistaken for an option.
  • Double quotes around $tmp keep a path with spaces in one piece (lesson 55).

A Temporary Directory for Several Files

When a script needs more than one temporary file, create one temporary directory and put everything inside it. A single rm -rf removes it all, and there is only one path to keep track of:

workdir=$(mktemp -d)
trap 'rm -rf -- "$workdir"' EXIT
touch "$workdir/a.txt" "$workdir/b.txt"
mkdir "$workdir/sub"
touch "$workdir/sub/c.txt"

After the script ended, the directory and everything in it, including the subdirectory, were gone. mktemp -d creates the directory with mode 700, so other users cannot look inside while the script runs (lesson 113).

Order and Unset Variables

The trap refers to a variable, so it matters what that variable holds when the trap runs. If the trap is set first and the script exits before the variable is assigned, set -u turns the cleanup itself into an error:

set -u
trap 'rm -f -- "$tmp"' EXIT
exit 1
tmp=$(mktemp)
order.sh: line 1: tmp: unbound variable

There are three clean solutions:

  1. Set the trap immediately after mktemp, as in the basic pattern. There is no moment where the trap exists without the variable.
  2. Give the variable an empty value first and test it in the cleanup: tmp= followed by trap '[[ -n $tmp ]] && rm -f -- "$tmp"' EXIT.
  3. Use a default in the expansion: trap 'rm -f -- "${tmp-}"' EXIT. With an empty argument, rm -f does nothing and succeeds.

The second form ends with a test that is false when nothing was created. That does not change the script's exit status: a script whose EXIT trap ended with a failed [[ -n $tmp ]] still exited with 0. The exit status changes only if the trap itself calls exit.

When mktemp itself fails, there is nothing to clean up, and the script should stop with a clear message before relying on the variable:

tmp=$(mktemp -p /nonexistent) || { echo "cannot create temp file" >&2; exit 1; }
trap 'rm -f -- "$tmp"' EXIT
mktemp: failed to create file via template '/nonexistent/tmp.XXXXXXXXXX': No such file or directory
cannot create temp file

A Cleanup Function

Once there is more than one thing to clean up, a function is easier to read and maintain than a long trap string. A good cleanup function saves the exit status in its first line and passes it on at the end:

cleanup() {
    local rc=$?
    rm -f -- "$tmp"
    echo "cleanup done, exiting with $rc" >&2
    exit "$rc"
}
tmp=$(mktemp)
trap cleanup EXIT
false
exit 4
cleanup done, exiting with 4

The script ended with status 4. local rc=$? must be the very first command: any command before it, even an echo, would replace $?. Ending with exit "$rc" (or return "$rc", which also kept status 5 in a separate test) makes the final status explicit, so nothing inside the function can change it by accident.

Keep set -e Out of the Cleanup Path

A cleanup function runs under the same options as the rest of the script. Under set -e, a failing command in the cleanup stops the cleanup halfway:

set -e
cleanup() {
    rm -- "$tmp.missing"
    echo "second step"
}
tmp=$(mktemp)
trap cleanup EXIT
echo "body done"
body done
rm: cannot remove '/tmp/tmp.YaQ4GDZgzk.missing': No such file or directory

Three things went wrong at once: second step never ran, the real temporary file $tmp was not removed, and a script that had finished its work successfully exited with status 1. Write cleanup commands so they cannot fail: rm -f instead of rm, kill ... 2>/dev/null for processes that may already have ended, and tests such as [[ -n $var ]] before acting. With rm -f -- "$tmp.missing" "$tmp" the same script printed second step and exited with 0. In a longer cleanup function, set +e as its second line (after saving $?) is another option.

Making Signals Run the Cleanup Everywhere

Bash runs the EXIT trap when SIGINT or SIGTERM ends a script, but not every shell does. A Dash script with only an EXIT trap, sent SIGTERM while waiting, ended with status 143 and left its temporary file behind. Adding explicit signal traps that call exit fixes this, because exit always runs the EXIT trap:

tmp=$(mktemp)
trap 'rm -f -- "$tmp"; echo "dash cleanup ran"' EXIT
trap 'exit 143' TERM
trap 'exit 130' INT
sleep 5 &
wait
dash cleanup ran

The status was 143 and the file was removed. These extra traps also make the intent explicit in Bash, and they give the script a place to print a message such as "interrupted".

The cleanup still runs only once. In a Bash test with an EXIT trap and trap 'exit 130' INT, sending SIGINT printed cleanup called a single time and ended with status 130: the INT trap called exit, and exit ran the EXIT trap. Putting the cleanup command itself into the INT and TERM traps as well would run it twice, which is why the signal traps should only call exit.

Things Cleanup Cannot Cover

  • SIGKILL. kill -9 ends the process without running any trap (lesson 123). Keep temporary files in the system temporary directory, where the operating system or a periodic job can remove leftovers, rather than in the user's working folder.

  • exec. exec replaces the shell with another program, so the shell never exits and its EXIT trap never runs:

    tmp=$(mktemp)
    trap 'rm -f -- "$tmp"; echo "trap ran"' EXIT
    exec echo "replaced by echo"
    replaced by echo

    The trap did not run and the file stayed behind. Remove temporary files before an exec, or run the program normally and let the script exit afterwards.

  • Subshells. A subshell does not run the parent's EXIT trap. When a subshell creates its own temporary file, give it its own trap inside the parentheses; in the test, ( t=$(mktemp); trap 'rm -f -- "$t"' EXIT; ... ) removed the file when the subshell ended.

Stopping Background Processes

Background processes are also resources that a script should release. A process started with & keeps running after the script ends unless something stops it:

sleep 30 &
echo "main work done, no cleanup"

A check after the script ended showed the sleep process still running, orphaned. The cleanup function can stop it:

helper_pid=
cleanup() {
    if [[ -n $helper_pid ]]; then
        kill "$helper_pid" 2>/dev/null
        wait "$helper_pid" 2>/dev/null
        echo "helper $helper_pid stopped"
    fi
}
trap cleanup EXIT
sleep 30 &
helper_pid=$!
echo "main work done"
main work done
helper 660 stopped

Afterwards the process was gone. $! is the process ID of the last background command (lesson 139). wait collects the process after kill, so Bash does not later print a "Terminated" job message. Both commands send their errors to /dev/null because the helper may already have finished on its own.

Keeping Files for Debugging

When a script fails, its intermediate files are often the best evidence of what went wrong. An environment variable can switch the cleanup off on request:

workdir=$(mktemp -d)
cleanup() {
    local rc=$?
    if [[ -n ${KEEP_TMP-} ]]; then
        echo "keeping $workdir for inspection" >&2
    else
        rm -rf -- "$workdir"
    fi
    return "$rc"
}
trap cleanup EXIT
echo data > "$workdir/out.txt"

A normal run removed the directory. Run as KEEP_TMP=1 ./script.sh, it printed:

keeping /tmp/tmp.XXXXXXXXXX for inspection

and the directory was still there afterwards (the random part of the name differs on every run). ${KEEP_TMP-} keeps the test safe under set -u.

A Complete Example

This script merges several text files into one sorted list without duplicates. It works inside a temporary directory and only replaces the output file at the very end, so an error or an interruption never leaves a half-written output file or stray temporary files:

#!/usr/bin/env bash
# merge-lists.sh OUTPUT INPUT...: merge text files into OUTPUT, sorted and without duplicates
set -euo pipefail
prog=${0##*/}

workdir=
cleanup() {
    local rc=$?
    if [[ -n $workdir ]]; then
        rm -rf -- "$workdir"
    fi
    exit "$rc"
}
trap cleanup EXIT
trap 'echo "$prog: interrupted" >&2; exit 130' INT
trap 'echo "$prog: terminated" >&2; exit 143' TERM

if (( $# < 2 )); then
    echo "usage: $prog OUTPUT INPUT..." >&2
    exit 2
fi
out=$1
shift

workdir=$(mktemp -d)
echo "$workdir" > .last_workdir     # recorded only so the test can check it

# Step 1: copy every input, normalizing line endings
n=0
for f in "$@"; do
    n=$((n + 1))
    tr -d '\r' < "$f" > "$workdir/part$n"
done

# Step 2: merge (DELAY simulates a slow step for testing)
sleep "${DELAY:-0}"
sort -u "$workdir"/part* > "$workdir/merged"

# Step 3: replace OUTPUT in one step
mv -- "$workdir/merged" "$out"
echo "$prog: wrote $(wc -l < "$out") unique lines to $out"

a.txt held apple, banana and cherry; b.txt held banana, date and apple with Windows (CRLF) line endings. The .last_workdir line exists only so the test could check after each run that the work directory was removed:

./merge-lists.sh;                              echo "status $?"
./merge-lists.sh all.txt a.txt b.txt;          echo "status $?"
./merge-lists.sh all2.txt a.txt missing.txt;   echo "status $?"
DELAY=5 ./merge-lists.sh all3.txt a.txt b.txt & p=$!
sleep 1; kill -TERM "$p"; wait "$p";           echo "status $?"
usage: merge-lists.sh OUTPUT INPUT...
status 2
merge-lists.sh: wrote 4 unique lines to all.txt
status 0
./merge-lists.sh: line 32: missing.txt: No such file or directory
status 1
merge-lists.sh: terminated
status 143

all.txt contained apple, banana, cherry and date. After the failed run and the terminated run, neither all2.txt nor all3.txt existed, and in all three runs that created a work directory, it was removed.

How it works:

  • workdir= is set before the trap, and cleanup checks it, so an exit before mktemp (the usage error) does not try to remove anything.
  • The failed redirection < "$f" for the missing file stopped the script under set -e. Without a trap, part1 would have been left behind in /tmp.
  • SIGTERM arrived during sleep 5. As lesson 123 explained, Bash handled it when sleep finished; the TERM trap printed its message and called exit 143, which ran cleanup, which kept the status 143.
  • The output file is written only by the final mv. Before that line, the old OUTPUT (if any) is untouched; after it, the new file is complete. Because sort created merged normally rather than through mktemp, the result had the usual permissions (-rw-r--r-- here) rather than the 600 mode of a file made by mktemp (lesson 113). Moving from /tmp to another file system is a copy rather than an atomic rename; lesson 113 covers creating the temporary file next to the target when that matters.

The examples were run with Bash 5.2.21, Dash 0.5.12 and GNU coreutils 9.4 on Ubuntu 24.04. Temporary file names and process IDs differ on every run.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Cleaning Up Temporary Files on Exit and get answers drawn from it.

Signed-in readers only.