Skip to content

Instantly share code, notes, and snippets.

@ichramm
Created November 22, 2012 12:24
Show Gist options
  • Select an option

  • Save ichramm/4130908 to your computer and use it in GitHub Desktop.

Select an option

Save ichramm/4130908 to your computer and use it in GitHub Desktop.
bash args parser
#
# 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