Added gitignore entries needed to ignore derived objects generated from full build...
[bash.git] / examples / scripts.noah / mktmp.bash
blob3ea43ad9f4105fe0464800fd7101b28be1678eb5
1 # mktmp.bash
2 # Author: Noah Friedman <friedman@prep.ai.mit.edu>
3 # Created: 1993-02-03
4 # Last modified: 1993-02-03
5 # Public domain
7 # Conversion to bash v2 syntax done by Chet Ramey
9 # Commentary:
10 # Code:
12 #:docstring mktmp:
13 # Usage: mktmp [template] {createp}
15 # Generate a unique filename from TEMPLATE by appending a random number to
16 # the end.
18 # If optional 2nd arg CREATEP is non-null, file will be created atomically
19 # before returning. This is to avoid the race condition that in between
20 # the time that the temporary name is returned and the caller uses it,
21 # someone else creates the file.
22 #:end docstring:
24 ###;;;autoload
25 function mktmp ()
27 local template="$1"
28 local tmpfile="${template}${RANDOM}"
29 local createp="$2"
30 local noclobber_status
32 case "$-" in
33 *C*) noclobber_status=set;;
34 esac
36 if [ "${createp:+set}" = "set" ]; then
37 # Version which creates file atomically through noclobber test.
38 set -o noclobber
39 (> "${tmpfile}") 2> /dev/null
40 while [ $? -ne 0 ] ; do
41 # Detect whether file really exists or creation lost because of
42 # some other permissions problem. If the latter, we don't want
43 # to loop forever.
44 if [ ! -e "${tmpfile}" ]; then
45 # Trying to create file again creates stderr message.
46 echo -n "mktmp: " 1>&2
47 > "${tmpfile}"
48 return 1
50 tmpfile="${template}${RANDOM}"
51 (> "${tmpfile}") 2> /dev/null
52 done
53 test "${noclobber_status}" != "set" && set +o noclobber
54 else
55 # Doesn't create file, so it introduces race condition for caller.
56 while [ -e "${tmpfile}" ]; do
57 tmpfile="${template}${RANDOM}"
58 done
61 echo "${tmpfile}"
64 provide mktmp
66 # mktmp.bash ends here