Skip to content

Instantly share code, notes, and snippets.

@crashGoBoom
Created January 17, 2019 21:45
Show Gist options
  • Save crashGoBoom/70ed5645cc40f35994cae712949133c2 to your computer and use it in GitHub Desktop.
Save crashGoBoom/70ed5645cc40f35994cae712949133c2 to your computer and use it in GitHub Desktop.
Example of parsing sub commands in a function with getopts
function get_help() {
cat <<help_message
--- script subcommand -------------------------------------------------------------
Commands related to this script
USAGE:
script command shell [FLAGS] [SUBCOMMAND]
FLAGS:
-H Prints help information
SUBCOMMANDS:
all Do everything (blah, blah2) [default]
help_message
return 1
}
function get_opts() {
# Parse options to the main command.
while getopts ":H" opt; do
case "${opt}" in
H)
# Display help.
get_help
;;
\?)
# Unrecognized option, get help.
libs_log::error "Invalid option: -${OPTARG}"
get_help
;;
esac
done
shift $((OPTIND -1))
declare -grx CODE_SRC_DIR
# Remove the main command from the argument list.
local -r _subcommand="${1:-}"
if [[ -z ${_subcommand} ]]; then
echo "Do some default thing."
return 0
fi
shift
case "${_subcommand}" in
all)
echo "Do something like run_all_something"
exit 0
;;
*)
# Unrecognized option, get help.
echo "Invalid subcommand: ${_subcommand}!"
get_help
;;
esac
return 0
}
function main() {
get_opts "${@}"
return 0
}
main "${@}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment