getopts recall getopts syntax etc  # getopts optstring opt [ arg ... ] # # Reads an option from arg ..., at position OPTIND; fails at end of arg list. # arglist stops at single '-' or at first word not starting with '-' (ksh: '+') # arg ...: arguments to analyse (defaults to "$@") # optstring: option letters - if letter followed by ':', that option requires # an argument, to be read into OPTARG. If optstring does not start # :optstring - unknown option: opt='?', $OPTARG= # - missing arg: opt=':', $OPTARG= # optstring - unknown option: opt='?', stderr message, OPTARG unset # - missing arg: opt='?', stderr message, OPTARG unset # opt: variable name will be set to the recognised option letter, or # on error '?' or ':' (see optstring). # OPTIND: index of next argument to read: set it to 1 to restart # OPTARG: set to an option argument (if any) # For ksh: options starting with '+' rather than '-': opt=+ # For bash: OPTERR (initially 1): if not set to 1, no stderr messages on error # ------------------------------------------------------------------------------ # reset options counter (only set to 1 automatically for new shells) OPTIND=1 while getopts :s:l opt "$@"; do if [[ "$opt" == : ]]; then echo "Option -$OPTARG requires an argument" >&2 fi case "$opt" in # Flag: l) l_opt=1 ;; # Option with argument s) s_opt="$OPTARG" ;; # Invalid arguments: ':') echo "Option -$OPTARG requires an argument" && usage && exit 1 ;; '?') echo "Invalid option: -$OPTARG" && usage && exit 1 ;; *) echo "Option error: $opt" && usage && exit 1 ;; esac done # forget the options in the command line now shift $(($OPTIND - 1)) # ksh, bash shift `expr $OPTIND - 1` # sh # ------------------------------------------------------------------------------