I've noticed this before, but it was brought up again as I was answering "How to move directory into a directory with the same name?":
The mktemp utility on macOS does not behave the same as the utility of the same name on Linux or BSD (or least OpenBSD) with respect to the TMPDIR environment variable.
To create a temporary file in the current directory, I can usually say
tmdfile=$(TMPDIR=. mktemp)
or
tmpfile=$(TMPDIR=$PWD mktemp)
(and similarly for a temporary directory with mktemp -d).
On macOS, I will have to force the utility to use the current directory by giving it an actual template, as in
tmpfile=(mktemp ./tmp.XXXXXXXX)
because using the more convenient tmpfile=$(TMPDIR=. mktemp) would ignore the TMPDIR variable and create the file under /var/folders/qg/s5jp5ffx2p1fxv0hy2l_p3hm0000gn/T or in a similarly named directory.
The manual for mktemp on macOS mentions that
If the
-t prefixoption is given,mktempwill generate a template string based on the prefix and the_CS_DARWIN_USER_TEMP_DIRconfiguration variable if available. Fallback locations if_CS_DARWIN_USER_TEMP_DIRis not available areTMPDIRand/tmp.
On my system, _CS_DARWIN_USER_TEMP_DIR appears to be unset:
$ getconf _CS_DARWIN_USER_TEMP_DIR
getconf: no such configuration parameter `_CS_DARWIN_USER_TEMP_DIR'
but e.g.
tmpfile=$(TMPDIR=. mktemp -t hello)
still creates a file under /var/folders/.../ (also when using $PWD in place of .).
I'm noticing that
$ getconf DARWIN_USER_TEMP_DIR
/var/folders/qg/s5jp5ffx2p1fxv0hy2l_p3hm0000gn/T/
but this doesn't help me much as I wouldn't know how to change this value.
The macOS mktemp utility is said to come from FreeBSD, which in turn got it from OpenBSD (which must have been quite a while ago).
Question:
Is this a bug (or omission) in the macOS implementation of mktemp? How do I change the DARWIN_USER_TEMP_DIR value (or _CS_DARWIN_USER_TEMP_DIR mentioned by the manual) from within a script (I would ideally want to unset it so that $TMPDIR takes precedence)?
TMPDIRin preference to any other place, and themktempfrom MacOS was changed to useconfstr(_CS_DARWIN_USER_TEMP_DIR). Based on what I've skimmed from this guys analysis, I don't think you can change the path returned by that. Keep usingmktempwith a template._CS_DARWIN_USER_TEMP_DIRvariable could be unset or changed somehow, or whether there are situations where it would be unset. Why would there be a fallback to$TMPDIRotherwise? Also, since it's inherited from OpenBSD via FreeBSD, I was expecting it to behave similarly.