#!/bin/bash # Script showing use of getopt and here documents # # This script allows options of -m, -i, or -h or --help # It doesn't really do anything, but it does show # sophisticated command line argument processing # and several advanced shell programming features. # Note the "-m" option has a required argument, # as does the equivalent "--mode" option. # # Written 2005 by Wayne Pollock, Tampa Florida USA. #set -x # uncomment this line to turn on debug mode PATH=/bin:/usr/bin # This strips off the pathname info from the scriptname, # ("$0"), leaving just the last (filename) part: SCRIPTNAME=${0##*/} # To avoid a lot of echo commands (and associated # quoting issues) in some show_help function, you # can use a "here" document. A "here" document # is an embedded file within the script. # Here's a sample: function show_help() { cat <<-EOF $SCRIPTNAME: You are beyond any help, so stop annoying me!!! :-) ... EOF } # Parse out the args into a standard format: ARGS=$(getopt -n $SCRIPTNAME -o m:ih -l mode:,help -- "$@") # if the getopt detected an error, display help and quit: if [ $? -ne 0 ] then show_help exit 1; fi # Now reset the positional parameters: # (The "eval" is needed in case any args were quoted by getopt.) eval set -- $ARGS # Handle each arg. Usually this is a matter of setting # some variable, to be tested later in the script. # This loop processes each option, one at a time, until # the end of options is found (marked with "--"). This # code removes each arg as it is processed, so at the # end, the positional parameters contain only the non-option # command line args (for instance, filenames to work with): M_OPT=0 M_ARG='' I_OPT=0 DONE=false while [ "$DONE" != "true" ] do case "$1" in -m|--mode) let '++M_OPT' case "$2" in -*) echo "*** Missing argument: $1" >&2; exit 1;; *) M_ARG="$2"; shift ;; esac ;; -i) let '++I_OPT' ;; -h|--help) show_help ;; --) DONE=true ;; *) echo "***Illegal option: $1" >&2; exit 1 ;; esac shift # this deletes $1 and resets the positional parameters done # At this point, the positional parameters contain the # remaining command line arguments (not options), if any. # Rest of script goes here: ... echo M_OPT=$M_OPT, M_ARG=$M_ARG, I_OPT=$I_OPT echo remaining cmd line args: $*