Skip to content

Instantly share code, notes, and snippets.

@psolru
Last active July 9, 2022 21:29
Show Gist options
  • Save psolru/18c6bba06881f652b06b92b5f8d78136 to your computer and use it in GitHub Desktop.
Save psolru/18c6bba06881f652b06b92b5f8d78136 to your computer and use it in GitHub Desktop.
Little bash CLI "parser"
#!/bin/bash
FOO="foooo"
BAR="baaaaar"
BAZ="baaaazzz"
function help() {
echo "A command-line interface for foo, bar and baz."
echo
echo "Example Usage:"
echo -e "\t ./cli-parser.sh -f fo -b bra -B bza"
echo
echo "Available Parameters:"
echo -e "\t -h|--help \t Show this help"
echo -e "\t -f|--foo \t Specify foo"
echo -e "\t -b|--bar \t Specify bar"
echo -e "\t -B|--baz \t Specify bar"
exit 0
}
POSITIONAL_ARGS=()
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help)
help
;;
-f|--foo)
FOO="$2"
shift # past argument
shift # past value
;;
-b|--bar)
BAR="$2"
shift # past argument
shift # past value
;;
-B|--baz)
BAZ="$2"
shift # past argument
shift # past value
;;
-*|--*)
echo "Unknown option $1"
exit 1
;;
*)
POSITIONAL_ARGS+=("$1") # save positional arg
shift # past argument
;;
esac
done
set -- "${POSITIONAL_ARGS[@]}" # restore positional parameters
echo "Given params:"
echo -e "\t FOO: ${FOO}"
echo -e "\t BAR: ${BAR}"
echo -e "\t BAZ: ${BAZ}"
################################################################
################################################################
# OUTPUT EXAMPLE OF HELP PAGE
#
# $ ./cli-parser.sh --help
# A command-line interface for foo, bar and baz.
#
# Example Usage:
# script.sh -f
#
# Available Parameters:
# -h|--help Show this help
# -f|--foo Specify foo
# -b|--bar Specify bar
# -B|--baz Specify bar
#
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment