Last active
August 29, 2015 14:04
-
-
Save detj/bad684d55eb476957669 to your computer and use it in GitHub Desktop.
How to parse arguments using getopts
This file contains hidden or 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/sh | |
# Uses getopts to parse passed arguments | |
# Show usage | |
show_help() { | |
cat << EOF | |
Usage: echoback -m message | |
Echo back whatever is passed as message | |
-h display this help and exit | |
-v be verbose | |
-m string that should be echoed back | |
EOF | |
} | |
VERBOSE=0 | |
OPTIND=1 | |
while getopts "hvm:" opt; do | |
case "$opt" in | |
# Show usage and exit | |
h) | |
show_help | |
exit 0 | |
;; | |
# Verbose mode on | |
v) | |
VERBOSE=1 | |
echo 'Verbose mode is on' | |
;; | |
# Echo the message back | |
m) | |
echo $OPTARG | |
exit $? | |
;; | |
esac | |
done | |
shift "$((OPTIND-1))" | |
show_help |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try