Created
October 2, 2020 15:18
-
-
Save webb/ff380b0eee96dafe1c20c2a136d85ef0 to your computer and use it in GitHub Desktop.
A simple CLI parser in Bash
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 | |
print_help () { echo "Option -f \${file}: Set file"; exit 0; } | |
fail () { echo "Error: $*" >&2; exit 1; } | |
unset file | |
OPTIND=1 | |
while getopts :f:h-: option | |
do case $option in | |
h ) print_help;; | |
f ) file=$OPTARG;; | |
- ) case $OPTARG in | |
file ) fail "Option \"$OPTARG\" missing argument";; | |
file=* ) file=${OPTARG#*=};; | |
help ) print_help;; | |
help=* ) fail "Option \"${OPTARG%%=*}\" has unexpected argument";; | |
* ) fail "Unknown long option \"${OPTARG%%=*}\"";; | |
esac;; | |
'?' ) fail "Unknown short option \"$OPTARG\"";; | |
: ) fail "Short option \"$OPTARG\" missing argument";; | |
* ) fail "Bad state in getopts (OPTARG=\"$OPTARG\")";; | |
esac | |
done | |
shift $((OPTIND-1)) | |
echo "File is ${file-unset}" | |
for (( i=1; i<=$#; ++i )) | |
do printf "\$@[%d]=\"%s\"\n" $i "${@:i:1}" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment