Skip to content

Instantly share code, notes, and snippets.

@codeindulgence
Last active October 3, 2018 12:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save codeindulgence/af022c8dbc2bc33a92b55caae46be006 to your computer and use it in GitHub Desktop.
Save codeindulgence/af022c8dbc2bc33a92b55caae46be006 to your computer and use it in GitHub Desktop.
Shell argument parsing boilerplate
#! /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