tags:

views:

585

answers:

5

I wrote a short bash script to complete a task that involves creating a temporary directory and storing various files in it and performing various operations on it.

In my first pass I just created the temp dir at /tmp/$$.$script", but then I tested the script on a computer where I didn't have write access to /tmp/, and I'd like to take that case into account. So my question is where's a good secondary location for this temp dir? Should I just use the current directory? The home directory? ~/tmp/? The output location of the script?

All created files do get cleaned up on script exit.

+1  A: 

You could try /var/tmp, although it's likely that /tmp is a symlink to that (or vice-versa).

Adam Rosenfield
In this particular case I do actually have access to /var/temp, so that's what I'm going with. Thanks.
Lawrence Johnston
+7  A: 

Many systems also have a /var/tmp. If the sysadmin doesn't want you writing in to /tmp, presumably they have provided some alternative… is the $TMPDIR environment variable set? For example, on my Mac:

$ echo $TMPDIR
/var/folders/jf/jfu4pjGtGGGkUuuq8HL7UE+++TI/-Tmp-/
Graham Lee
Unfortunately this particular computer does not have TMPDIR set, but I think I will add a check for that as a possible write location. Thanks.
Lawrence Johnston
+5  A: 

I would suggest ~/.[your script name]/tmp, if TMPDIR is not set, instead of ~/tmp/ since the user may have created that on their own (and you may not want to accidentally override things in there).

Just as an off the cuff thought in bash --

case $TMPDIR in '') tmp_dir=".${0}/tmp";; *) tmp_dir=$TMPDIR;; esac
rnicholson
+4  A: 

Use ${TMPDIR:-/tmp} ($TMPDIR or /tmp if $TMPDIR is not set). If that's not writable, then exit with an error saying so, or ask the user for input defining it. I think asking the user where temp files should go is preferable to assuming somewhere and leaving them there if your process gets killed.

Evan Krall
+1  A: 

You could try using mktemp (assuming it's configured correctly for the system)

e.g. MYTMPDIR=$(mktemp -d)

Nick