There's a sentence that puts all of us at ease when we write a temporary file:
"the system will clean it up anyway." macOS keeps that promise partly — and I
didn't know where the partly ended until I counted. The temp directory on my
own Mac holds 5,359 entries today. 4,779 of them are directories. Of the 3,236
directories older than three days, 3,037 are completely empty, and not one of
them gets deleted.
The promise holds in a narrow place: files at the top level of that
directory. There isn't a single file up there that hasn't been accessed in
three days — the rule works flawlessly. The moment you open a subdirectory the
picture changes: that directory is never collected, and the fate of what's
inside it becomes unpredictable. The same tree holds 2,973 files and 0.96 GiB
that nothing has touched in over three days.
This article is about where that boundary sits, how to audit your own temp
directory, and how to clean up after yourself. Every number on the Mac side
comes from one machine: macOS 26.6.2 (build 25G83), Darwin 25.6.0 arm64, Node
v22.16.0, Python 3.13.3, Perl v5.34.1, Ruby 2.6.10. The census was taken at
17:11 on 23 November 2026.
The rule is out in the open
The confstr(3) manual states the policy in one sentence: files in this
location may be removed by the system if they are not accessed in three days.
The job that enforces it isn't hidden either:
$ plutil -p /System/Library/LaunchDaemons/com.apple.bsd.dirhelper.plist
{
"EnablePressuredExit" => true
"EnvironmentVariables" => { "CLEAN_FILES_OLDER_THAN_DAYS" => "3" }
"Label" => "com.apple.bsd.dirhelper"
"MachServices" => { "com.apple.bsd.dirhelper" => true }
"ProcessType" => "Adaptive"
"ProgramArguments" => [ 0 => "/usr/libexec/dirhelper" ]
"RunAtLoad" => true
"StartCalendarInterval" => { "Hour" => 3, "Minute" => 35 }
}
Every day at 03:35, plus every boot. The variable's name sums the rule up in
one word: CLEAN_FILES_OLDER_THAN_DAYS. Files. Not directories.
The /tmp side has a separate job, com.apple.tmp_cleaner, which runs at
midnight. Two directories, two schedules.
Measuring the boundary
First, where the rule works. The top level of the temp directory:
$ T=$(getconf DARWIN_USER_TEMP_DIR)
$ /usr/bin/find "$T" -maxdepth 1 -mindepth 1 -type f | wc -l
564
$ /usr/bin/find "$T" -maxdepth 1 -mindepth 1 -type f -atime +3 | wc -l
0
564 files, none of them untouched for more than three days. The manual's
sentence is literally true here. (I kept the same criterion the manual uses:
access time. Looking at -mtime instead showed one file; the rule watches
access.)
Now the whole tree:
$ /usr/bin/find "$T" -type f | wc -l
15612
$ /usr/bin/find "$T" -type f -atime +3 | wc -l
2973
$ /usr/bin/find "$T" -type f -atime +3 -print0 | xargs -0 du -ck | tail -1
1006612 total
2,973 files nobody has touched in over three days, 0.96 GiB. All of them inside
subdirectories. And the directories themselves:
$ /usr/bin/find "$T" -maxdepth 1 -mindepth 1 -type d | wc -l
4779
$ /usr/bin/find "$T" -maxdepth 1 -mindepth 1 -type d -mtime +3 | wc -l
3236
$ /usr/bin/find "$T" -maxdepth 1 -mindepth 1 -type d -mtime +3 -empty | wc -l
3037
3,037 of the 3,236 old directories are empty. Being empty, they occupy no
space — du puts them at 0 KiB. The cost here isn't disk, it's entry count:
over five thousand entries in a single directory, and every ls reads all of
them.
That they are empty is an important clue: the files that used to be inside them
were removed at some point. I can't claim the system never descends into
subdirectories — clearly it does. Yet 2,973 files are still sitting there. I
couldn't derive a rule that explains both at once; /usr/libexec/dirhelper
isn't open source, and reverse-engineering its behavior isn't this article's
job. The practical conclusion is clear enough: there's a guarantee for files
at the top level, and none from the moment you open a directory.
I should also say that I never watched a deletion happen.
launchctl print system/com.apple.bsd.dirhelper reports that the job has run
26 times in eighteen days, but log show --predicate 'process == "dirhelper"'
comes back empty. My evidence is the run count and the absence of old files at
the top level; the deletion itself I did not witness.
How long this debris took to pile up
Looking at creation times gives a sharp boundary: all 5,359 entries were born
after the boot at 08:56 on 5 November, the oldest at 08:57. Not a single entry
predates it. The same holds for /tmp.
So these three thousand directories are the product of a single eighteen-day
session. For anyone who doesn't shut the machine down for months, it isn't
hard to guess where the number goes. The only thing that truly sweeps this
directory is a restart.
Counting who left them
Applying a pattern to the names of the old empty directories lines the culprits
up:
$ /usr/bin/find "$T" -maxdepth 1 -type d -mtime +3 -empty |
sed -E 's/[0-9A-Za-z_]{6,}$/<random>/' | sort | uniq -c | sort -rn | head -4
1093 BlobRegistryFiles-<random>
590 .<random>
517 kimi-node-repl-session-<random>
198 content-metadata-<random>
The first is WebKit, the third a REPL tool I use. The fourth one stopped me:
the content-metadata- prefix comes from this blog's own repository.
$ git grep -n "mkdtempSync" -- scripts/
scripts/tests/content-topic-deferrals.test.mjs:13: const dir = fs.mkdtempSync(...'content-deferral-');
scripts/tests/reconcile-content-metadata.test.mjs:9: const dir = mkdtempSync(join(tmpdir(), 'content-metadata-'));
scripts/tests/reconcile-content-metadata.test.mjs:44: const dir = mkdtempSync(join(tmpdir(), 'content-metadata-'));
The first file deletes what it opens (rmSync on line 38). The second doesn't.
Two tests, two directories, no cleanup. The measurement:
$ node --test scripts/tests/reconcile-content-metadata.test.mjs >/dev/null
$ # before 350, after 352
Exactly two directories per run. There are 352 on disk — meaning this single
test file has run hundreds of times and left two folders behind every time.
What's inside is predictable too: current.json, local.json, current.last,
local.last. Four files, in every directory.
That's where the real lesson of this article collects. My own test file opens a
directory through a library call (mkdtempSync) and never closes it; the system
never collects the directory; the files inside sometimes go and sometimes stay.
If all three links worked perfectly this wouldn't accumulate — the behavior of
the other two only matters because the first one is broken.
Where the directory you're auditing actually is
To run that census you need the right path, and on macOS that's harder than it
looks. The path isn't /tmp, and the TMPDIR variable won't change it:
$ env -i /usr/bin/getconf DARWIN_USER_TEMP_DIR
/var/folders/nn/fmy2b8m575143sfsvs3wrfz40000gn/T/
$ env TMPDIR=/private/tmp /usr/bin/getconf DARWIN_USER_TEMP_DIR
/var/folders/nn/fmy2b8m575143sfsvs3wrfz40000gn/T/
The second line matters: pointing TMPDIR at a different directory changed
nothing. That value doesn't come from the environment, it comes from Apple's
dirhelper — the very job that enforces the cleanup rule also creates the
directory. The chain is right there in Libc's open-source confstr.c: asking
for _CS_DARWIN_USER_TEMP_DIR calls __dirhelper(DIRHELPER_USER_LOCAL_TEMP, ...),
and only if that fails does it try TMPDIR and then P_tmpdir (that is,
/tmp). The comment in the source puts it plainly: "If __dirhelper() fails,
try TMPDIR and P_tmpdir, finally failing otherwise."
The confstr(3) manual spells out the directory's contract as well: created if
missing, opened 0700, restricted by the calling process's umask. Its
siblings come with different contracts: DARWIN_USER_DIR (.../0/) is created
0755 and the manual warns about it openly — don't put sensitive data there,
every user can see it. DARWIN_USER_CACHE_DIR (.../C/) is not cleaned
automatically by the system; the manual names one exception, it is removed
during a safe boot.
What mktemp listens to, and what it doesn't
mktemp uses the same chain, and that makes it deaf to TMPDIR. Six
experiments produced the picture; A = /private/tmp, B = a directory I
created for the test:
| Condition | where mktemp -t pfx wrote |
|---|---|
no TMPDIR, no -p
|
/var/folders/.../T/ |
TMPDIR=A, no -p
|
/var/folders/.../T/ — TMPDIR ignored
|
no TMPDIR, -p=B
|
B |
TMPDIR=A, -p=B
|
B |
TMPDIR=A, -p '' (empty) |
A |
TMPDIR=A, explicit template |
the template's own path |
A single precedence chain doesn't explain those six rows; there are three
branches. With no -p at all, confstr wins and TMPDIR never gets a turn.
With a non-empty -p, that directory is used directly. With an empty -p,
TMPDIR is consulted, and confstr steps in only if that is missing too. The
source builds this with a flag set in two places: prefer_tmpdir goes false
both while -p is processed and in the implied -t mode with no arguments.
What the manual page says about this doesn't line up. The -p entry says "use
tmpdir for the -t flag if the TMPDIR environment variable is not set";
the fourth row of the table shows the opposite. The -t entry only says "using
the supplied prefix and TMPDIR if set" and never describes the behavior on
Apple platforms. That sentence is inherited from FreeBSD; the macOS code has a
separate branch behind #ifdef __APPLE__.
I've written before about which authority resolves a command name on this same
machine —
I typed grep, I got ugrep.
That question was about which program runs; this one is about which
directory gets written to, and the authority answering it isn't a shell table
but a system service.
Two halves of a script can look in two directories
That deafness has an everyday cost. The shell opens the file with mktemp, the
Node half looks for it with os.tmpdir(). In a terminal the two agree. In an
environment that carries no TMPDIR — a scheduler job, a hand-started service,
a container — they don't:
kabuk yazdi: /var/folders/nn/fmy2b8m575143sfsvs3wrfz40000gn/T/rapor.Es3kyfAiFk
node baktigi dizin: /tmp
node HATA: ENOENT /tmp/rapor.Es3kyfAiFk
The shell didn't budge; Node moved. With TMPDIR empty, mktemp and Ruby pick
the system's directory while Node, Python and Perl drop to /tmp. Python
documents it: gettempdir() consults TMPDIR, TEMP and TMP in order, then
/tmp, /var/tmp and /usr/tmp, and as a last resort the current working
directory — so in the bad case your temporary file lands inside your project.
If you wonder where TMPDIR comes from: not your shell. launchctl getenv returns nothing, yet it sits in the environment of every job launchd
TMPDIR
starts. I defined a one-shot job and dumped its environment; thirteen variables
came back:
$ launchctl submit -l tr.mustafaerbay.tmpdirlab -o out -e err -- \
/bin/sh -c 'env | sort'
$ cat out
HOME=/Users/mustafaerbay
LOGNAME=mustafaerbay
OSLogRateLimit=64
PATH=/usr/bin:/bin:/usr/sbin:/sbin
PWD=/
SHELL=/bin/zsh
SHLVL=1
SSH_AUTH_SOCK=/var/run/com.apple.launchd.58yayOiLJQ/Listeners
TMPDIR=/var/folders/nn/fmy2b8m575143sfsvs3wrfz40000gn/T/
USER=mustafaerbay
XPC_FLAGS=0x0
XPC_SERVICE_NAME=0
_=/usr/bin/env
PATH is minimal, TMPDIR is in place. Your terminal is a child of launchd
too, which is why you always see it populated; outside that domain the variable
is gone.
Why the permission difference matters
Dropping to /tmp doesn't only mean "file not found":
$ ls -ld /private/tmp "$TMPDIR"
drwxrwxrwt 530 root wheel 16960 Nov 23 16:39 /private/tmp
drwx------@ 5344 mustafaerbay staff 171008 Nov 23 16:39 /var/folders/nn/.../T/
/tmp is sticky and world-writable; counting with ls -A gave 528 entries
inside it. The personal temp directory is 0700. On a single-user laptop the
difference stays academic; on a shared build machine it doesn't. And there the
main risk isn't listability: creating a file with a predictable name in a shared
directory leaves the door open to the classic symlink race. I've written about
the protection mechanics of a shared /tmp on the Linux side —
root and still unable to write to /tmp.
One more detail: this directory is per user, not per session. Two sessions
opened by the same user share the same T directory.
Linux behaves differently
Before writing the recipe I asked the same questions on my own server — Ubuntu
24.04.5, GNU coreutils 9.4:
$ echo "TMPDIR=[$TMPDIR]"
TMPDIR=[]
$ env -i getconf DARWIN_USER_TEMP_DIR
getconf: Unrecognized variable `DARWIN_USER_TEMP_DIR'
$ env -i /usr/bin/mktemp -t lab.XXXXXX
/tmp/lab.5MsQzj
$ env TMPDIR=/var/tmp /usr/bin/mktemp -t lab.XXXXXX
/var/tmp/lab.PDED89
TMPDIR is already empty in an interactive shell; nobody injects a personal
directory for you. There is no such query as DARWIN_USER_TEMP_DIR, so that
call can't be part of a portable recipe. And GNU mktemp honors TMPDIR as
written. The macOS manual's "TMPDIR if set" sentence isn't wrong — it's
another system's truth.
The recipe
Resolve the directory once, and resolve it above both steps. My first
attempt put it in the wrong place: I exported TMPDIR inside the first script,
and because Node ran as a sibling process in the second one the ENOENT
continued unchanged. The variable belongs in the common ancestor of both
steps. Portability needs an emptiness check too, because on Linux getconf
returns nothing and the variable ends up "set but empty":
# in the wrapper, before both steps
: "${TMPDIR:=$(getconf DARWIN_USER_TEMP_DIR 2>/dev/null)}"
[ -n "$TMPDIR" ] || TMPDIR=/tmp
export TMPDIR
./hazirla.sh && node oku.js
Don't trust the convention on a critical path. TMPDIR is a general
contract, not the agreement between your two steps. A variable with your own
name on it, or a command-line argument, protects you when someone changes
TMPDIR for another purpose six months from now.
Whoever opens the directory closes it. In shell the price is two lines, and
the condition matters so a failed mktemp doesn't turn into rm -rf on an
empty variable:
d=$(mktemp -d -t isim) || exit 1
trap '[ -n "$d" ] && rm -rf "$d"' EXIT INT TERM
INT and TERM belong on that list; schedulers and CI runners have a habit of
cutting jobs short. The Node equivalent is
fs.rmSync(d, { recursive: true, force: true }) inside a finally — exactly
the line missing from my own test file.
Write the variable into the service definition yourself. If you're writing a
LaunchAgent or LaunchDaemon, put TMPDIR into the plist's
EnvironmentVariables dictionary by hand. Apple's dirhelper plist already
does this.
Don't try to tune the three days. That plist lives under
/System/Library/LaunchDaemons/, which is SIP-protected. Build your own
cleanup instead of changing the number.
Measure the pile before you delete it. One line that only looks:
find "$(getconf DARWIN_USER_TEMP_DIR)" -maxdepth 1 -mindepth 1 \
-type d -mtime +3 -empty | wc -l
If the number has four digits, clearing them is harmless; empty directories
older than three days are by definition of no use to anyone. Before touching the
non-empty ones, look inside — it could be the working area of a running service.
Rather than doing this by hand once a month, put a threshold in a LaunchAgent of
your own and have it tell you when the count passes your number.
Checklist
- Does every
mktemp -d/mkdtempSyncyou open have a matchingtraporfinally? - Can that
traprunrm -rfon an empty variable? - Are the parts of your script that produce and consume the temp path in the same process tree?
- Did you set
TMPDIRand assumemktempwould honor it? It doesn't;-pdoes. - Can sensitive intermediate data land in
/tmp? If it can, the permission model drops from0700to1777. - How many empty directories piled up in your temp directory over the last eighteen days?
Closing
What stays with me isn't mktemp's precedence order, it's how late I noticed
that the contract is narrow. The system makes me a promise about a file, and I
leave behind a tree, assuming the promise covers the tree. Three thousand empty
directories are the eighteen-day invoice for that assumption.
The location and the lifetime of a temporary file need to be written down rather
than assumed. The rmSync line missing from my own test file is the cheapest
form of that; until I write it, the counter keeps ticking.
Top comments (0)