How to create a temporary directory?

Xiè Jìléi picture Xiè Jìléi · Jan 8, 2011 · Viewed 141.8k times · Source

I use to create a tempfile, delete it and recreate it as a directory:

temp=`tempfile`
rm -f $temp
  # <breakpoint>
mkdir $temp

The problem is, when it runs to the <breakpoint>, there happens to be another program wants to do the same thing, which mkdir-ed a temp dir with the same name, will cause the failure of this program.

Answer

moinudin picture moinudin · Jan 8, 2011

Use mktemp -d. It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.