Home | History | Annotate | Download | only in examples
      1 #!/bin/sh
      2 #
      3 # This script takes a filename as input and writes the current date to the
      4 # file. If the file already exists, it will not be overwritten unless the '-f'
      5 # (or '--force') flag is given.
      6 #
      7 # This script demonstrates several types of shFlags functionality.
      8 # - declaration of the FLAGS_HELP variable to customize the help output
      9 # - direct calling of the flags_help() function for script controlled usage
     10 #   output
     11 # - handling of non-flag type command-line arguments that follow the flags
     12 #
     13 # Try the following:
     14 # $ ./write_date.sh now.out
     15 # $ cat now.out
     16 #
     17 # $ ./write_date.sh now.out
     18 # $ cat now.out
     19 #
     20 # $ ./write_date.sh -f now.out
     21 # $ cat now.out
     22 
     23 # source shflags
     24 . ../src/shflags
     25 
     26 # configure shflags
     27 DEFINE_boolean 'force' false 'force overwriting' 'f'
     28 FLAGS_HELP="USAGE: $0 [flags] filename"
     29 
     30 
     31 write_date()
     32 {
     33   date >"$1"
     34 }
     35 
     36 die()
     37 {
     38   [ $# -gt 0 ] && echo "error: $@" >&2
     39   flags_help
     40   exit 1
     41 }
     42 
     43 
     44 # parse the command-line
     45 FLAGS "$@" || exit 1
     46 eval set -- "${FLAGS_ARGV}"
     47 
     48 # check for filename
     49 [ $# -gt 0 ] || die 'filename missing'
     50 filename=$1
     51 
     52 [ -f "${filename}" -a ${FLAGS_force} -eq ${FLAGS_FALSE} ] \
     53     && die 'filename exists; not overwriting'
     54 write_date "${filename}"
     55