I'm looking at a bash script someone else wrote that uses mktemp:TEMP=`mktemp --directory`However, this line does not work on my machine (OS X 10.6).How would I fix this line so that it is cross-un*x-like-platform compatible? EDIT: An alternative command would be sufficient as well.
Fix or alternative for mktemp in OS X
shell script;osx;utilities
The following is what I ended up using to reliably create a temporary directory that works on both Linux and Darwin (all versions before Mac OS X 10.11), without hardcoding $TMPDIR or /tmp:mytmpdir=`mktemp -d 2>/dev/null || mktemp -d -t 'mytmpdir'`Background:The GNU mktemp command requires no arguments. Plain mktemp will create a temporary file in the system temporary directory.Plain mktemp -d will create a temporary directory, which is what you'd want to use on Linux.(gnu-coreutils)$ man mktemp# If DIR is not specified, uses $TMPDIR if set, else /tmp.By default it uses template tmp.XXXXXXXXXX expanded relative to the default temporary directory.OSX's mktemp command requires this template, it has no default. The syntax for the template on OSX is compatible with that of GNU's. OSX's mktemp has a -t option that means something else. The -t option is documented as prefix. It is expanded to $TMPDIR/{prefix}.XXXXXXXX, so it adds the Xs to it automatically (e.g. mktemp -d -t example could create $TMPDIR/example.zEJZWCTQ).I was surprised to find that in various Linux environments $TMPDIR is not set by default (many tools support it when set, but still have to default to /tmp). Which meant passing $TMPDIR/example.XXXXXXXX to mktemp or mkdir was not an option (as it would cause the path to end up as a subdirectory of the root directory).On OSX $TMPDIR is always set and (at least in the default shell) it is not set to /tmp (which is a symlink to /private/tmp) but to /var/folders/dx/*****_*************/T. So we should honour that if we can.In conclusion the following is what I ended up using to reliably create a temporary directory that works on both Linux and Darwin (Mac OS X), without hardcoding $TMPDIR or /tmp:mytmpdir=`mktemp -d 2>/dev/null || mktemp -d -t 'mytmpdir'`The first part is for Linux. This command will fail on Darwin (Mac OS X) with error status code 1 responding with usage: .... That's why we ignore stderr and instead then execute the Mac variant. The mytmpdir prefix is only used on Mac.