Skip to content

Instantly share code, notes, and snippets.

@tomschr
Last active July 24, 2024 08:09
Show Gist options
  • Save tomschr/5241afb1b95eb15d2351b5a8ce5f5c83 to your computer and use it in GitHub Desktop.
Save tomschr/5241afb1b95eb15d2351b5a8ce5f5c83 to your computer and use it in GitHub Desktop.
Bash Example for Parsing Command Line Arguments
#!/bin/bash
#
# A simple example of how to parse CLI options and arguments
## === variable Declarations
# Script name without any directories ("basename"):
PROG=${0##*/}
# Version information:
VERSION="1.0.0"
# Verbosity level:
VERBOSE=0
# Arguments, the rest after parsing all options:
ARGS=""
## === Functions
function usage() {
cat << EOF
SYNOPSIS
$PROG [-v]...
$PROG --version
$PROG -h|--help
$PROG
OPTIONS
-v, -vv, -vvv.. Raise verbosity level
-h, --help Display this help and exit
--version Output version information and exit
EOF
}
function parsecli()
{
# For details about getopt,
# see https://www.tutorialspoint.com/unix_commands/getopt.htm
local options=$(getopt -n "$PROG" -o v,h -l version,help -- "$@")
[ $? -eq 0 ] || {
echo "Incorrect option provided"
exit 1
}
eval set -- "$options"
while true; do
case "$1" in
-v)
VERBOSE=$(($VERBOSE + 1))
;;
-h|--help)
usage
;;
--version)
echo "$PROG $VERSION"
exit
;;
--)
shift
break
;;
esac
shift
done
# Remove script name:
shift
ARGS="$@"
}
parsecli $0 "$@"
echo "VERBOSE=$VERBOSE"
echo "ARGS=$ARGS"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment