Last active
March 23, 2017 03:20
-
-
Save akatrevorjay/5524111 to your computer and use it in GitHub Desktop.
Python-esque arguments for Bash. If you like this, check out https://github.com/akatrevorjay/bashism
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 -e | |
# ____________ | |
# getkwargs.sh | |
# | |
# -- Gives you simple Python-esque arguments in Bash | |
# ie: your_function_or_script never=always sync daemon=True | |
# | |
# TODO Enhance interface with standard opts support: -p|--path[=blah] | |
# | |
# ~trevorj 05/05/2013 | |
function getkwargs() { | |
local -A kwargs=() | |
local -a args=() | |
local kw_re='^([a-zA-Z][a-zA-Z0-9_]*)=(.+)$' | |
local k= v= | |
for v in "$@"; do | |
if [[ "$v" =~ $kw_re ]]; then | |
kwargs[${BASH_REMATCH[1]}]="${BASH_REMATCH[2]}" | |
else | |
args[${#args[@]}]="$v" | |
fi | |
done | |
## Bash will munge the newlines during expansion if it's being expanded, | |
## so we need to make sure that there are no newlines, with a seperator. | |
echo "$(declare -p args)"";""$(declare -p kwargs)" | |
} |
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 -e | |
## | |
## Example usage | |
## | |
. getkwargs.sh | |
function getkwargs_example() { | |
# Turn off verbose mode | |
set +v | |
# Simple | |
eval "$(getkwargs "$@")" | |
# <br /> | |
echo | |
# Print structure of args and kwargs | |
declare -p args kwargs | |
# Positional | |
echo "First positional argument is \"${args[0]}\"" | |
echo "Second positional argument is \"${args[1]}\"" | |
# Keyword | |
local k= v= | |
for k in "${!kwargs[@]}"; do | |
v="${kwargs[$k]}" | |
echo "Keyword argument \"$k\"=\"$v\"" | |
done | |
# <br /> | |
echo | |
# Turn verbose mode back on | |
set -v | |
} | |
# Turn on verbose mode to output what we're running below | |
set -v | |
getkwargs_example omg=yes=yes2 arg0 arg1 munch=faces=whatsits | |
getkwargs_example "omg=yes=yes2 arg0" "arg1 munch=faces=whatsits" | |
getkwargs_example "omg=yes=yes2 arg0" "arg1 munch=faces=whatsits" | |
getkwargs_example "omg=yes=yes2 arg0" "arg1 munch=faces=whatsits" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment