Skip to content

Instantly share code, notes, and snippets.

@rbecheras
Last active December 12, 2017 16:47
Show Gist options
  • Save rbecheras/de4291fe3329f5c7610c82ca086d78ab to your computer and use it in GitHub Desktop.
Save rbecheras/de4291fe3329f5c7610c82ca086d78ab to your computer and use it in GitHub Desktop.
Proof of concept of handling unix-like options in shell scripts
#!/usr/bin/env bash
optspec=":hv-:"
while getopts "$optspec" optchar; do
case "${optchar}" in
-)
case "${OPTARG}" in
loglevel)
val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
echo "Parsing option: '--${OPTARG}', value: '${val}'" >&2
;;
loglevel=*)
val=${OPTARG#*=}
opt=${OPTARG%=$val}
echo "Parsing option: '--${opt}', value: '${val}'" >&2
;;
*)
if [ "$OPTERR" = 1 ] && [ "${optspec:0:1}" != ":" ]; then
echo "Unknown option --${OPTARG}" >&2
fi
;;
esac;;
h)
echo "usage: $0 [-v] [--loglevel[=]<value>]" >&2
exit 2
;;
v)
val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
echo "Parsing option: '-${optchar}', value: '${val}'" >&2
;;
*)
if [ "$OPTERR" != 1 ] || [ "${optspec:0:1}" = ":" ]; then
echo "Non-option argument: '-${OPTARG}'" >&2
fi
;;
esac
done
@rbecheras
Copy link
Author

To test the script:

$ ./bash-getops.sh

$ ./bash-getops.sh -v 
usage: ./testargs.sh [-v] [--loglevel[=]<value>]

etc...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment