while [[ $# -gt 0 ]]; do case$1in -e|--extension) EXTENSION="$2" shift# past argument shift# past value ;; -s|--searchpath) SEARCHPATH="$2" shift# past argument shift# past value ;; --default) DEFAULT=YES shift# past argument ;; -*|--*) echo"Unknown option $1" exit 1 ;; *) POSITIONAL_ARGS+=("$1") # save positional arg shift# past argument ;; esac done
set -- "${POSITIONAL_ARGS[@]}"# restore positional parameters
for i in"$@"; do case$iin -e=*|--extension=*) EXTENSION="${i#*=}" shift# past argument=value ;; -s=*|--searchpath=*) SEARCHPATH="${i#*=}" shift# past argument=value ;; --default) DEFAULT=YES shift# past argument with no value ;; -*|--*) echo"Unknown option $i" exit 1 ;; *) ;; esac done
#!/bin/bash # More safety, by turning some bugs into errors. set -o errexit -o pipefail -o noclobber -o nounset
# ignore errexit with `&& true` getopt --test > /dev/null && true if [[ $? -ne 4 ]]; then echo'I’m sorry, `getopt --test` failed in this environment.' exit 1 fi
# -temporarily store output to be able to check for errors # -activate quoting/enhanced mode (e.g. by writing out “--options”) # -pass arguments only via -- "$@" to separate them correctly # -if getopt fails, it complains itself to stderr PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@") || exit 2 # read getopt’s output this way to handle the quoting right: evalset -- "$PARSED"
d=n f=n v=n outFile=- # now enjoy the options in order and nicely split until we see -- whiletrue; do case"$1"in -d|--debug) d=y shift ;; -f|--force) f=y shift ;; -v|--verbose) v=y shift ;; -o|--output) outFile="$2" shift 2 ;; --) shift break ;; *) echo"Programming error" exit 3 ;; esac done
# handle non-option arguments if [[ $# -ne 1 ]]; then echo"$0: A single input file is required." exit 4 fi