Last active
October 18, 2016 06:57
-
-
Save murarisumit/c07b5095127466e137b9e1a2f0df9d74 to your computer and use it in GitHub Desktop.
Bash basic template for argument parsing and basic exit handling
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/bash | |
## | |
# the handle_argument function receives all the non-option argument or non-flag argument | |
## | |
handle_argument() { | |
# the first argumeent without any flag | |
echo " Argument is : $1 " | |
} | |
# Send error to STDERR | |
err() { | |
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $@" >&2 | |
} | |
while [ "$#" -gt 0 ]; do | |
case "$1" in | |
-f) format="$2"; shift 2;; | |
-l) logfile="$2"; shift 2;; | |
--format=*) format="${1#*=}"; shift 1;; | |
--logfile=*) logfile="${1#*=}"; shift 1;; | |
--format|--logfile) echo "$1 requires an argument" >&2; exit 1;; | |
-*) echo "unknown option: $1" >&2; exit 1;; | |
*) handle_argument "$1"; shift 1;; | |
esac | |
done | |
err "I'm done here" | |
exit 0 | |
#Ref: http://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment