Last active
August 29, 2021 00:28
-
-
Save ar2pi/0d61686e9c16671a39197139588e94c1 to your computer and use it in GitHub Desktop.
Bash argument parser
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
#!/usr/bin/env bash | |
# | |
# An over-engineered bash argument parser | |
# Inspired from *args and **kwargs in Python | |
# | |
# Usage: | |
# parse_args "$@" | |
# | |
# Examples: | |
# script.sh 10 20 | |
# args: [10, 20] | |
# kwargs: [] | |
# script.sh --foo bar --baz qux 10 20 | |
# args: [10, 20] | |
# kwargs: [foo: bar, baz: qux] | |
# script.sh -x 3 -y 2 -z -- 10 20 | |
# args: [10, 20] | |
# kwargs: [x: 3, y: 2, z: 1] | |
# | |
declare -a args | |
declare -A kwargs | |
function is_value () { | |
if [[ $(echo $1 | grep -cE "^-") = 0 ]]; then | |
return 0 | |
fi | |
return 1 | |
} | |
function parse_args () { | |
local arg | |
local value | |
while [[ $# -gt 0 ]]; do | |
if [[ $1 = "--" ]]; then | |
shift; continue | |
elif $(is_value $1); then | |
arg=$1 | |
else | |
arg=$(echo $1 | sed -nE "s/--?(.*)/\1/p") | |
fi | |
if [[ ! -z ${2+_} ]] && $(is_value $2) && ! $(is_value $1); then | |
kwargs[$arg]=$2 | |
shift | |
elif ! $(is_value $1); then | |
kwargs[$arg]=1 | |
else | |
args+=($arg) | |
fi | |
shift | |
done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment