Last active
December 23, 2015 17:39
-
-
Save tueda/6670080 to your computer and use it in GitHub Desktop.
mktemp_d makes a temporary directory and prints the path of it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/sh | |
# Wraps "mktemp -d $1XXXXXXXXXX" | |
mktemp_d() {( | |
umask 077 | |
{ | |
# Use mktemp if available. | |
dir=`mktemp -d "$1XXXXXXXXXX" 2>/dev/null` && [ -d "$dir" ] | |
} || { | |
# Fall back on mkdir. | |
dir= | |
i=0 | |
while [ $i -lt 100 ]; do | |
next_dir=$1$$$i$RANDOM$RANDOM | |
if mkdir "$next_dir" >/dev/null 2>&1; then | |
dir=$next_dir | |
break | |
fi | |
i=`expr $i + 1` | |
done | |
[ "x$dir" != x ] && [ -d "$dir" ] | |
} || { | |
echo "mktemp_d: failed to create a temporary directory" >&2 | |
exit 1 | |
} | |
echo "$dir" | |
)} | |
# Typical use. | |
tmpdir=`mktemp_d "${TMPDIR:-/tmp}/tmp"` | |
trap 'rm -rf "$tmpdir"' 0 1 2 13 15 | |
# Do something on files created in the temporary directory here. | |
touch "$tmpdir/tmp1" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment