#!/bin/bash ## Illustrates getopts. usage() { ## ${0##*/} is a builtin equivalent to $( basename $0 ) echo >&2 Usage: $( basename $0 ) \ '{-a|-b} [-cCde] [-o outfile] [-t type] file [file...]' exit 1 } ## Make some variables local so that they are initialized to null. typeset flag_ab flag_cC flag_d flag_e flag_t arg_t outputfile ## Alternately use seven lines like # flag_ab= while getopts abcCdeo:t: opt do case $opt in a) if [ "$flag_ab" != "" ] ; then usage ; else flag_ab=a_seen fi ;; b) if [ "$flag_ab" != "" ] ; then usage ; else flag_ab=b_seen fi ;; c|C) flag_cC=set ;; d) flag_d=set ;; e) flag_e=set ;; o) outputfile="$OPTARG" ;; t) flag_t=set arg_t="$OPTARG" ;; ## The next two patterns show how to override the default messages. ## To use, put an initial colon on the getopts string like this: ## while getopts :abcCdeo:t: opt ## \?) echo >&2 Unknown option: -"$OPTARG" usage ;; :) echo >&2 Option -"$OPTARG" requires argument usage ;; ## If you don't use the two patterns above then just do this instead: *) usage ;; esac done ## At this point OPTIND will be position of next argument (the first operand). shift $(( OPTIND - 1 )) ## Shift off all options and arguments. if [[ "$flag_ab" = "" ]] ; then echo >&2 Must select one of -a or -b usage fi if [[ $# = 0 ]] ; then echo >&2 Need a file operand usage fi ## Done with option processing. Body goes below. echo "Flags: $flag_ab flag_cC=$flag_cC flag_d=$flag_d flag_e=$flag_e" echo "Outputfile: $outputfile" echo "Flag_t: $flag_t $arg_t" echo "Files: $*"