Skip to content

Instantly share code, notes, and snippets.

@wilcollins
Created February 4, 2018 05:21
Show Gist options
  • Save wilcollins/15319e0d0e74b4d977c725ce4b71f85a to your computer and use it in GitHub Desktop.
Save wilcollins/15319e0d0e74b4d977c725ce4b71f85a to your computer and use it in GitHub Desktop.
Parses long & short flags in a single block
#!/bin/bash
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd )"
# ----- defaults -----
SOME_FLAG=false
# ----- arg parsing -----
show_help(){
cat <<EOF
Usage: [options]
-h| --help show this help text
-sf| --some-flag do something
EOF
}
while :; do
case $1 in
-h|-\?|--help)
show_help
exit
;;
-sf|--some-flag)
SOME_FLAG=true
;;
--) # End of all options.
shift
break
;;
-?*)
printf 'WARN: Unknown option (ignored): %s\n' "$1" >&2
;;
*) # Default case: No more options, so break out of the loop.
break
esac
shift
done
# Handle positional arguments
if [ -n "$*" ]; then
echo "Extra arguments -- $*"
echo "Try '-h' for more information."
exit 1
fi
# ----- end arg parsing -----
set -u
if [ $SOME_FLAG = true ]; then
echo "do something"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment