Created
August 9, 2020 20:26
-
-
Save mangalbhaskar/7b19616fe9ddfbc0923b71b220fbfe51 to your computer and use it in GitHub Desktop.
key value parser for shell script for bash shell
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 | |
## Copyright (c) 2020 mangalbhaskar. All Rights Reserved. | |
##__author__ = 'mangalbhaskar' | |
##---------------------------------------------------------- | |
## key value parser for shell script for bash shell | |
## Reference and Credits: | |
## http://tldp.org/LDP/abs/html/parameter-substitution.html | |
## https://stackoverflow.com/questions/14370133/is-there-a-way-to-create-key-value-pairs-in-bash-script#14371026 | |
## https://stackoverflow.com/questions/5499472/specify-command-line-arguments-like-name-value-pairs-for-shell-script | |
## @Example: | |
## ./argparse.sh --x="blah" | |
## ./argparse.sh --x="blah" --yy="qwert bye" | |
## ./argparse.sh x="blah" yy="qwert bye" | |
##---------------------------------------------------------- | |
set -u | |
: ${1? | |
'Usage: | |
$0 --<key1>="<val1a> <val1b>" [ --<key2>="<val2a> <val2b>" | --<key3>="<val3>" ]' | |
} | |
declare -A args | |
while [[ "$#" > "0" ]]; do | |
case "$1" in | |
(*=*) | |
_key="${1%%=*}" && _key="${_key/--/}" && _val="${1#*=}" | |
args[${_key}]="${_val}" | |
(>&2 echo -e "key:val => ${_key}:${_val}") | |
;; | |
esac | |
shift | |
done | |
(>&2 echo -e "Total args: ${#args[@]}; Options: ${args[@]}") | |
## This additional can check for specific key | |
[[ -n "${args['path']+1}" ]] && (>&2 echo -e "key: 'path' exists") || (>&2 echo -e "key: 'path' does NOT exists"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In order to use the argparse as a modular script in utility function, save the following as
argparse.sh
:And now it can be included in other functions in different scripts. Let's say there's another script called as
test-argparse.sh
; assuming bothargparse.sh
andtest-argparse.sh
are saved in the same directory,Now execute
test-argparse.sh
:Output will be: