Skip to content

Instantly share code, notes, and snippets.

@fcenobi
Forked from mangalbhaskar/argparse.sh
Last active July 30, 2022 01:20
Show Gist options
  • Save fcenobi/a60cfe70a6ba89ee567a5888f82fd6ad to your computer and use it in GitHub Desktop.
Save fcenobi/a60cfe70a6ba89ee567a5888f82fd6ad to your computer and use it in GitHub Desktop.
key value parser for shell script for bash shell
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
#!/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");
function test-1-case-1-argparse() {
local LSCRIPTS=$( cd "$( dirname "${BASH_SOURCE[0]}")" && pwd )
source ${LSCRIPTS}/argparse.sh "$@"
echo "Total: $# should be equal to ${#args[@]} and args: ${args[@]}"
local key
for key in "${!args[@]}"; do
[[ -n "${args[${key}]+1}" ]] && echo "${key} = ${args[${key}]}" || echo "Key does not exists: ${key}"
done
}
test-1-case-1-argparse --user='blah' --group='dummy' --uid=1111 --gid=0000
function test-1-case-1-argparse() {
local LSCRIPTS=$( cd "$( dirname "${BASH_SOURCE[0]}")" && pwd )
source ${LSCRIPTS}/argparse.sh "$@"
echo "Total: $# should be equal to ${#args[@]} and args: ${args[@]}"
local key
for key in "${!args[@]}"; do
[[ -n "${args[${key}]+1}" ]] && echo "${key} = ${args[${key}]}" || echo "Key does not exists: ${key}"
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment