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
6
7# Conversion to bash v2 syntax done by Chet Ramey
8
9# Commentary:
10# Code:
11
12#:docstring mktmp:
13# Usage: mktmp [template] {createp}
14#
15# Generate a unique filename from TEMPLATE by appending a random number to
16# the end. 
17#
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:
23
24###;;;autoload
25function mktmp ()
26{
27    local template="$1"
28    local tmpfile="${template}${RANDOM}"
29    local createp="$2"
30    local noclobber_status
31
32    case "$-" in
33    *C*)	noclobber_status=set;;
34    esac
35
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
49          fi
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
59    fi
60
61    echo "${tmpfile}"
62}
63
64provide mktmp
65
66# mktmp.bash ends here
67