Jerry Krinock
Jerry Krinock

Reputation: 5020

mktemp fails when used in bash script

In Mac OS X, I have no trouble with mktemp when used in Terminal directly, but the same command in a bash script fails. What am I doing wrong?

DIRECTLY:

Air2:~ jk$ mktemp -t "$0"

/var/folders/dq/g6bjxff136515xqlntckj0hc0000gn/T/-bash.74Kw3y9E

SCRIPT:

#!/bin/sh
mktemp -t "$0"

SCRIPT RUN:

Air2:~ jk$ ~/Desktop/Temp/junk.sh

mktemp: mkstemp failed on /var/folders/dq/g6bjxff136515xqlntckj0hc0000gn/T//Users/jk/Desktop/Temp/junk.sh.VrRRi9qE: No such file or directory
Air2:~ jk$ 

Upvotes: 4

Views: 4331

Answers (1)

Chandranshu
Chandranshu

Reputation: 3669

You don't have a directory named /var/folders/dq/g6bjxff136515xqlntckj0hc0000gn/T//Users/jk/Desktop/Temp/.

Notice that $0 is ~/Desktop/Temp/junk.sh when you use it in the bash script and the ~ gets expanded as well. So, rather than creating a simple temporary file in the current directory, mktemp is now trying to create the file in a directory 4 levels deep from the current directory. Since it doesn't exist, your command fails.

From the man page of mktemp:

   -t     interpret TEMPLATE as a single file name component, relative to a 
          directory: $TMPDIR, if set; else the  directory specified via -p;
          else /tmp [deprecated]

So, there you have it from the horse's mount. The parameter to -t should be a single file name component and not a path value.

Upvotes: 3

Related Questions