Usually, the command line tool for creating temporary directories is called mktemp
, not mkstemp
. I'm not sure if it's safe to use on all platforms. If it isn't, you can attempt to make a directory with a strict umask
and fail when the directory already exists.
mkdtemp() {
old_mask=$(umask)
umask 077
name="/tmp/tmp.$$.$RANDOM"
mkdir "$name" && echo "$name"
retval=$?
umask $old_mask
return $retval
}
Usage:
tempdir=$(mkdtemp) || report_failure
Since this tries to create the directory (an atomic operation) instead of checking whether it exists and fails when the name it generates is taken, this operation is safe. It is prone to a denial-of-service attack, though, where an attacker creates many temporary directories just to let the above function fail.