Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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