Last active
November 25, 2020 08:00
-
-
Save kolodny/3979f0bd9c9cb609a28b00ad77428890 to your computer and use it in GitHub Desktop.
args.sh
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/sh | |
set -euo pipefail | |
#declare valid arguments here | |
bar= | |
baz= | |
function parse_args() { | |
args=() | |
local i=1 | |
while [ $i -le $# ]; do | |
local arg="${!i}" | |
case "${arg}" in | |
--*=*) | |
arg=${arg#--} | |
local key="${arg%=*}" | |
if [ ! ${!key+x} ]; then | |
echo "invalid option -- $key" 1>&2 | |
exit 2 | |
fi | |
local value="${arg#*=}" | |
eval $key=\$value | |
;; | |
--?*) | |
local key=${arg#--} | |
if [ ! ${!key+x} ]; then | |
echo "invalid option -- $key" 1>&2 | |
exit 2 | |
fi | |
if [ $i -ge $# ]; then | |
echo "option requires an argument -- $key" 1>&2 | |
exit 2 | |
fi | |
let "i++" | |
local value=${!i} | |
eval $key=\$value | |
;; | |
*) | |
args+=("$arg") | |
esac | |
let "i++" | |
done | |
} | |
parse_args "$@" | |
echo "bar is $bar" | |
echo "baz is $baz" | |
for arg in "${args[@]}"; do | |
echo "arg is $arg" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment