Last active
February 27, 2020 09:17
-
-
Save dominik-ba/2d70e4cbf71ebeafb3936da08cf41bf1 to your computer and use it in GitHub Desktop.
Linux bash argument parsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Author: Dominik Bartsch | |
usage=" | |
Usage: $(basename "$0") [OPTIONS] | |
A tool to gather several infromation about the OpenShift projects/namespaces and capacity | |
Options: | |
-h, --help Show this help text | |
-f, --foo Do the foo thing | |
-b, --bar Do the bar thing | |
-s, --summary <detail> (Default Behavior) Shows the complete summary. | |
If detail is provided more details are shown. | |
" | |
function help () { | |
echo "$usage" | |
} | |
invalid_option="Invalid Option $1" | |
function error () { | |
echo | |
echo "$invalid_option" | |
help | |
} | |
# Transform long options to short ones | |
for arg in "$@"; do | |
shift | |
case "$arg" in | |
"--help") | |
set -- "$@" "-h" ;; | |
"--foo") | |
set -- "$@" "-f" ;; | |
"--bar") | |
set -- "$@" "-b" ;; | |
"--summary") | |
set -- "$@" "-s" ;; | |
"--"*) | |
error ${arg}; | |
exit 1 | |
;; | |
*) | |
set -- "$@" "$arg" | |
esac | |
done | |
while getopts ':h :f :b :s:' option | |
do | |
case "$option" in | |
h) | |
echo "$usage" | |
exit 0 | |
;; | |
f) | |
echo "Doing foo..." | |
foo_method | |
exit 0 | |
;; | |
b) | |
echo "Doing bar..." | |
bar_method | |
exit 0 | |
;; | |
s) | |
if [ "$OPTARG" == "detail" ] | |
then | |
echo "A optional arg was provided..." | |
detailed_summary_method | |
else | |
echo "No optional arg was provided..." | |
no_detailed_summary_method | |
fi | |
summary | |
exit 0 | |
;; | |
"?") | |
error "$OPTARG" | |
exit 1 | |
;; | |
esac | |
done | |
shift $((OPTIND - 1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment