Sample Header Ad - 728x90

mktemp on macOS not honouring $TMPDIR

13 votes
1 answer
3992 views
I've noticed this before, but it was brought up again as I was answering "https://unix.stackexchange.com/questions/555047 ": 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
-sh
tmdfile=$(TMPDIR=. mktemp)
or
-sh
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
-sh
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 prefix option is given, mktemp will generate a template string based on the prefix and the _CS_DARWIN_USER_TEMP_DIR configuration variable if available. Fallback locations if _CS_DARWIN_USER_TEMP_DIR is not available are TMPDIR and /tmp. On my system, _CS_DARWIN_USER_TEMP_DIR appears to be unset:
-none
$ getconf _CS_DARWIN_USER_TEMP_DIR
getconf: no such configuration parameter `_CS_DARWIN_USER_TEMP_DIR'
but e.g.
-sh
tmpfile=$(TMPDIR=. mktemp -t hello)
still creates a file under /var/folders/.../ (also when using $PWD in place of .). I'm noticing that
-none
$ 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)?
Asked by Kusalananda (354449 rep)
Dec 1, 2019, 03:03 PM
Last activity: Dec 2, 2019, 04:25 PM