Last active
December 12, 2017 16:47
-
-
Save rbecheras/de4291fe3329f5c7610c82ca086d78ab to your computer and use it in GitHub Desktop.
Proof of concept of handling unix-like options in shell scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To test the script:
etc...