Skip to content

Instantly share code, notes, and snippets.

@rpearce
Last active January 19, 2023 01:12
Show Gist options
  • Save rpearce/0ccab8013cc5de2ca64290ff9a3d72df to your computer and use it in GitHub Desktop.
Save rpearce/0ccab8013cc5de2ca64290ff9a3d72df to your computer and use it in GitHub Desktop.
Bash argument parsing program template
#!/bin/bash
set -o errexit
set -o errtrace
set -o nounset
set -eou pipefail
# ==============================================================================
VERSION="0.1.0"
AUTHOR="Robert W. Pearce"
SCRIPT_NAME="${0##*/}"
VERSION_SHORT="$SCRIPT_NAME version $VERSION"
VERSION_LONG="\
$VERSION_SHORT
Author: $AUTHOR"
bold=$(tput bold)
normal=$(tput sgr0)
HELP="\
This is a helpful description.
${bold}USAGE${normal}
$SCRIPT_NAME <command> [flags]
${bold}FLAGS${normal}
-h, -?, --help
Print the help menu
-v, --version
Print version information
-f <arg>, --foo <arg>
Pass an argument for foo
${bold}EXAMPLES${normal}
$ $SCRIPT_NAME -h
$ $SCRIPT_NAME --version
$ $SCRIPT_NAME --foo bar
"
# ==============================================================================
function print_help {
echo "$HELP" # | less -FRX
}
function print_version {
echo "$VERSION_LONG"
}
function print_error {
echo "$1" >&2
}
# ==============================================================================
function parse_args {
if [[ -z "$*" ]]; then
echo "No arguments provided"
exit 1
fi
# local all_args=("$@")
while :; do
local flag="${1:-}"
local flag_val="${2:-}"
case "$flag" in
# Help menu
-h|-\?|--help)
print_help
exit 0
;;
# Version
-v|--version)
print_version
exit 0
;;
# Foo flag
-f|--foo)
if [ "$flag_val" ]; then
echo "--foo value: $flag_val"
shift # past arg
shift # past val
else
print_error "error: --foo requires a non-empty argument"
exit 1
fi
;;
# Foo: handle equals syntax
--foo=?*)
local foo_val=${1#*=} # Delete everything up to "=" and assign the remainder
echo "--foo=?* value is $foo_val"
shift # past arg
;;
# Foo: handle equals syntax wih no value
--foo=)
print_error "error: --foo requires a non-empty argument"
exit 1
;;
# End of all flags
--)
shift # past arg
shift # past val
break
;;
# Unknown flag
-?*)
# printf "warn: unknown flag (ignored): %s\n" "$flag" >&2
print_error "warn: unknown flag (ignored): $flag"
shift # past arg
;;
# Default case, no more options
*)
break
;;
esac
done
}
# ==============================================================================
function main {
parse_args "$@"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment