Created
November 22, 2012 12:24
-
-
Save ichramm/4130908 to your computer and use it in GitHub Desktop.
bash args parser
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
| # | |
| # Parses and argument from the command line | |
| # the format must be arg <value> | |
| #Ex: | |
| # parse_arg result "-ip" "$@" | |
| # [[ $? -eq 0 ]] && echo "IP: $result" || echo "Param -ip not found" | |
| # parse_arg result "-m" "$@" | |
| # [[ $? -eq 0 ]] && echo "MSG: $result" || echo "Param -m not found" | |
| # where your command line arguments could be: -ip 127.0.0.1 -m "Hello Mr. Sapiens" | |
| # | |
| function parse_arg() | |
| { | |
| [[ -n "$1" ]] && [[ -n "$2" ]] && [[ -n "$3" ]] || return -1; | |
| __ret_var_name__=$1;shift | |
| argName=$1;shift; | |
| until [ -z "$1" ]; do | |
| [[ "$1" == "$argName" ]] && eval $__ret_var_name__="'$2'" && return 0; | |
| shift; | |
| done | |
| return -1; | |
| } | |
| # | |
| # or using getopts | |
| while getopts “ht:r:p:v” OPTION; do | |
| case $OPTION in | |
| h) | |
| usage | |
| exit 1 | |
| ;; | |
| i) | |
| IP=$OPTARG | |
| ;; | |
| p) | |
| POSRT=$OPTARG | |
| ;; | |
| ?) | |
| usage | |
| exit | |
| ;; | |
| esac | |
| done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment