Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

shell

macos

In Linux this shell script is suppose 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

Anyone know what is wrong? Thank you.

like image 266
user40780 Avatar asked Jul 14 '15 03:07

user40780


1 Answers

On Mac OS X, the -t option to mktemp takes an argument, which is a prefix for the temporary file/directory's name. On Linux, the -t argument just indicates that the prefix should either be the value of $TMPDIR or some default, usually /tmp.

So on Mac OS X, the invocation mktemp -t -d zombie.XXXXXXXXX, signifies -twith an argument is -d; consequently, mktemp creates a file whose name starts with -d inside $TMPDIR (/var/folders/d8/b8d1j9x94l9fr3y21xrnc0640000gn/T/-d.QZDPA9Da). Then, the template argument is 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 newline separator). Hence, the cd fails.

For a platform-independent call, avoid the -t flag and use an explicit template:

mktemp -d "${TMPDIR:-/tmp}/zombie.XXXXXXXXX"
like image 136
rici Avatar answered Sep 23 '22 11:09

rici