#! /bin/sh # tempfile (Bourne_shell script) -- Mimics tempfile command from 'debianutils' package # # Version: 1.0 # Copyright: (c)2021 Alastair Irvine # Keywords: # Notice: # Licence: This file is released under the GNU General Public License # # Description: # # # Usage: # Options: # # # Licence details: # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at # your option) any later version. # # See http://www.gnu.org/licenses/gpl-2.0.html for more information. # # You can find the complete text of the GPLv2 in the file # /usr/share/common-licenses/GPL-2 on Debian systems. # Or see the file COPYING in the same directory as this program. # # # TO-DO: SELF=`basename "$0"` ALLOWED_OPTIONS=p:s:d:m:n: ALLOWED_LONG_OPTIONS=prefix,suffix,directory,mode,name,help,version # *** FUNCTIONS *** show_help() { cat << EOT_HELP Usage: ${SELF} [OPTION] Create a temporary file in a safe manner. -d, --directory=DIR place temporary file in DIR -m, --mode=MODE open with MODE instead of 0600 -n, --name=FILE use FILE instead of tempnam(3) -p, --prefix=STRING set temporary file's prefix to STRING -s, --suffix=STRING set temporary file's suffix to STRING --help display this help and exit --version output version information and exit EOT_HELP } # *** MAINLINE *** # == command-line parsing == # -- defaults -- debug=0 verbose=0 prefix=file dir=/tmp # -- option handling -- set -e orthogonal_opts=$(getopt --shell=sh --name=$SELF \ --options=+$ALLOWED_OPTIONS --longoptions=$ALLOWED_LONG_OPTIONS -- "$@") eval set -- "$orthogonal_opts" set +e # getopt would have already reported the error while [ x"$1" != x-- ] ; do case "$1" in -m|--mode) mode=$2 ; shift ;; -n|--name) filename=$2 ; shift ;; -p|--prefix) prefix=$2 ; shift ;; -s|--suffix) suffix=$2 ; shift ;; -d|--dir) dir=$2 ; shift ;; -h|--help) show_help ; exit ;; --version) echo "${SELF} fake" ; exit ;; -1) echo "${SELF}: Warning: Blah blah blah feature unsupported" >&2 ;; esac shift # get rid of option (or if the inner shift already did, get rid of arg) done shift # get rid of the "--" # -- argument checking -- ## if [ $# != 2 -a $# != 3 ] ; then ## ## echo "Usage: $SELF ..." >&2 ## show_help >&2 ## exit 1 ## fi # -- argument handling -- # == sanity checking == # == preparation == # Note that the semantics of `tempfile` are that -d does NOT take precedence # over $TMPDIR if [ -z "$TMPDIR" ] ; then TMPDIR=$dir fi # Don't rely on PATH to be set safely if [ -x /usr/bin/mktemp ] ; then mktemp=/usr/bin/mktemp elif [ -x /bin/mktemp ] ; then mktemp=/bin/mktemp else echo "mktemp not found" >&2 exit 2 fi # == processing == if [ -z "$filename" ] ; then template=$(printf "%sXXXXXX%s" "$prefix" "$suffix") filename=$($mktemp --tmpdir=$TMPDIR -t "$template") else touch "$filename" fi echo "$filename" if [ -n "$mode" ] ; then chmod "$mode" "$filename" fi