diff options
Diffstat (limited to 'examples/write_date.sh')
-rwxr-xr-x | examples/write_date.sh | 47 |
1 files changed, 28 insertions, 19 deletions
diff --git a/examples/write_date.sh b/examples/write_date.sh index b8e610b..d9ae3ec 100755 --- a/examples/write_date.sh +++ b/examples/write_date.sh @@ -20,35 +20,44 @@ # $ ./write_date.sh -f now.out # $ cat now.out -# source shflags -. ../src/shflags +# Source shFlags. +. ../shflags -# configure shflags +# Configure shFlags. DEFINE_boolean 'force' false 'force overwriting' 'f' FLAGS_HELP="USAGE: $0 [flags] filename" - -write_date() -{ - date >"$1" -} - -die() -{ - [ $# -gt 0 ] && echo "error: $@" >&2 +die() { + [ $# -gt 0 ] && echo "error: $@" flags_help exit 1 } - -# parse the command-line +# Parse the command-line. FLAGS "$@" || exit 1 eval set -- "${FLAGS_ARGV}" -# check for filename -[ $# -gt 0 ] || die 'filename missing' +# Check for filename on command-line. +[ $# -gt 0 ] || die 'filename missing.' filename=$1 -[ -f "${filename}" -a ${FLAGS_force} -eq ${FLAGS_FALSE} ] \ - && die 'filename exists; not overwriting' -write_date "${filename}" +# Redirect STDOUT to the file ($1). This seemingly complicated method using exec +# is used so that a potential race condition between checking for the presence +# of the file and writing to the file is mitigated. +if [ ${FLAGS_force} -eq ${FLAGS_FALSE} ] ; then + [ ! -f "${filename}" ] || die "file \"${filename}\" already exists." + # Set noclobber, redirect STDOUT to the file, first saving STDOUT to fd 4. + set -C + exec 4>&1 >"${filename}" # This fails if the file exists. +else + # Forcefully overwrite (clobber) the file. + exec 4>&1 >|"${filename}" +fi + +# What time is it? +date + +# Restore STDOUT from file descriptor 4, and close fd 4. +exec 1>&4 4>&- + +echo "The current date was written to \"${filename}\"." |