Skip to content

Instantly share code, notes, and snippets.

@kolodny
Last active November 25, 2020 08:00
Show Gist options
  • Save kolodny/3979f0bd9c9cb609a28b00ad77428890 to your computer and use it in GitHub Desktop.
Save kolodny/3979f0bd9c9cb609a28b00ad77428890 to your computer and use it in GitHub Desktop.
args.sh
#!/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