Why is mktemp on OS X broken with a command that worked on Linux?

On Linux, this shell script is supposed to work:

# Temporary directory for me to work in
myTEMP_DIR="$(mktemp -t -d zombie.XXXXXXXXX)"

# Change to temporary directory
cd "${myTEMP_DIR}"

      

However, when I perform this operation on my Mac, I get the following error:

dhcp-18-189-66-216:shell-scripting-sci-day2 myname$ myTEMP_DIR="$(mktemp -t -d zombie.XXXXXXXXX)"
dhcp-18-189-66-216:shell-scripting-sci-day2 myname$ cd "${myTEMP_DIR}"
-bash: cd: /var/folders/d8/b8d1j9x94l9fr3y21xrnc0640000gn/T/-d.QZDPA9Da
zombie.nwlEnHGDb: No such file or directory

      

Does anyone know what is wrong? Thank.

+3


source to share


1 answer


On Mac OS X, the parameter -t

for mktemp

takes an argument that is a prefix for the temporary filename / directory. On Linux, the argument -t

simply indicates that the prefix should be either a value $TMPDIR

or some default, usually /tmp

.

So, on Mac OS X, call mktemp -t -d zombie.XXXXXXXXX

means -t

with an argument -d

; hence mktemp

creates a file whose name starts with -d

inside $TMPDIR

( /var/folders/d8/b8d1j9x94l9fr3y21xrnc0640000gn/T/-d.QZDPA9Da

). The template argument is then used to create another file ( zombie.nwlEnHGDb

, in the current working directory). Finally, it prints both names to stdout where they become the value of your variable ${myTEMP_DIR}

(complete with a newline separator). Hence, it cd

fails.



For platform independent calls, don't use a flag -t

and use an explicit pattern:

mktemp -d "${TMPDIR:-/tmp}/zombie.XXXXXXXXX"

      

+14


source







All Articles