Making tmp Files and Directories On The Command Line

September - 2021

Use mktmp

See the examples from man mktmp

tempfoo=basename $0 TMPFILE=mktemp /tmp/${tempfoo}.XXXXXX || exit 1 echo "program output" >> $TMPFILE

To allow the use of $TMPDIR:

tempfoo=basename $0 TMPFILE=mktemp -t ${tempfoo} || exit 1 echo "program output" >> $TMPFILE

In this case, we want the script to catch the error itself.

tempfoo=basename $0 TMPFILE=mktemp -q /tmp/${tempfoo}.XXXXXX if [ $? -ne 0 ]; then echo "$0: Can't create temp file, exiting..." exit 1 fi


On mac, it'll use a directory something like:

/var/folders/dx/ypcmcxd53mb731bpkp_2p_vh0000gn/T/

That's what's set in $TMPDIR

It'll use $_CS_DARWIN_USER_TEMP_DIR if that's set instead. If neither of those are set, it'll fall back to /tmp