You can use it getopts, but I donβt like it because it is difficult to use and does not support long option names (not the POSIX version).
I recommend not using environment variables. There is too much risk of name clashes. For example, if your script reacts differently depending on the value of the environment variable ARCH, and it runs another script that (without your knowledge) also reacts to the environment variable ARCH, then you probably have a hard time finding an error that only appears occasionally.
This is the template I am using:
#!/bin/sh
usage() {
cat <<EOF
Usage: $0 [options] [--] [file...]
Arguments:
-h, --help
Display this usage message and exit.
-f <val>, --foo <val>, --foo=<val>
Documentation goes here.
-b <val>, --bar <val>, --bar=<val>
Documentation goes here.
--
Treat the remaining arguments as file names. Useful if the first
file name might begin with '-'.
file...
Optional list of file names. If the first file name in the list
begins with '-', it will be treated as an option unless it comes
after the '--' option.
EOF
}
log() { printf '%s\n' "$*"; }
error() { log "ERROR: $*" >&2; }
fatal() { error "$*"; exit 1; }
usage_fatal() { error "$*"; usage >&2; exit 1; }
foo="foo default value goes here"
bar="bar default value goes here"
while [ "$#" -gt 0 ]; do
arg=$1
case $1 in
--*'='*) shift; set -- "${arg%%=*}" "${arg#*=}" "$@"; continue;;
-f|--foo) shift; foo=$1;;
-b|--bar) shift; bar=$1;;
-h|--help) usage; exit 0;;
--) shift; break;;
-*) usage_fatal "unknown option: '$1'";;
*) break;;
esac
shift || usage_fatal "option '${arg}' requires a value"
done