Last active
February 9, 2017 09:07
-
-
Save ssledz/6a381604341c7dd975c7ea9e5ee1c391 to your computer and use it in GitHub Desktop.
Parsing command line arguments using getopts in bash
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 | |
DBG=0 | |
dbg() { | |
[[ $DBG == 1 ]] && (1>&2 echo "[DEBUG] : "$1) | |
} | |
info() { | |
echo "[INFO] : $1" | |
} | |
warn() { | |
echo "[WARN] : $1" | |
} | |
err() { | |
(1>&2 echo "[ERROR] : $1") | |
} | |
show_help() { | |
cat << EOF | |
Usage: ${0##*/} -p port [-d] [-h] arg1 arg2 ...argN | |
Application description. | |
-p port Port. | |
-d Dry run. | |
-h Print this help. | |
EOF | |
} | |
dry_run=0 | |
port= | |
while getopts ":p:dh" opt; do | |
case $opt in | |
p) | |
port=$OPTARG | |
;; | |
d) | |
dry_run=1 | |
;; | |
h) | |
show_help | |
exit 0 | |
;; | |
\?) | |
echo >&2 | |
echo " Invalid option: -$OPTARG" >&2 | |
show_help | |
exit 1 | |
;; | |
:) | |
echo >&2 | |
echo " Option -$OPTARG requires an argument" >&2 | |
show_help | |
exit 2 | |
;; | |
*) | |
show_help | |
exit 3 | |
;; | |
esac | |
done | |
shift $((OPTIND-1)) # Shift off the options and optional -- | |
required=(port) | |
for req in ${required[@]}; do | |
[[ -z ${!req} ]] && echo && echo " Please specify $req" && show_help && exit 1 | |
done | |
echo "Args: $*" | |
[[ $dry_run -eq 1 ]] && info "Dry run" | |
[[ $dry_run -eq 0 ]] && echo "Do something with port : $port" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on http://wiki.bash-hackers.org/howto/getopts_tutorial & http://mywiki.wooledge.org/BashFAQ/035