Last active
October 3, 2018 12:33
-
-
Save codeindulgence/af022c8dbc2bc33a92b55caae46be006 to your computer and use it in GitHub Desktop.
Shell argument parsing boilerplate
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 | |
# Parse commands and options | |
while [[ $# -gt 0 ]]; do | |
key="$1" | |
case $key in | |
# Boolean option | |
-h|--help) | |
_HELP=1 | |
;; | |
-v|--verbose) | |
_VERBOSE=1 | |
;; | |
# Key value option | |
-k|--key) | |
_KEY=$2 | |
shift | |
;; | |
*) | |
# Save unmatched arguments | |
_commands="$_commands $key" | |
;; | |
esac | |
shift || true | |
done | |
# Reset remaining, unmatched arguments | |
set -- $_commands | |
if [ "$_HELP" ]; then cat >&2 <<EOS | |
Usage: $0 [options] <arg1[, arg2, ...]> | |
Options: | |
-h,--help Show this help and exit | |
EOS | |
exit; fi | |
echo Verbose: $_VERBOSE | |
echo Key: $_KEY | |
echo Args: ${@} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment