bashtemporary-directory

How to create a temporary directory?


I used 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 that wants to do the same thing, which mkdir-ed a temp dir with the same name, will cause the failure of this program.

How should I make a temp directory instead of a file?


Solution

  • 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.