Skip to content

Instantly share code, notes, and snippets.

@richarddd
Created May 2, 2022 12:49
Show Gist options
  • Save richarddd/b5b657729aaeecd3de86ef0cfccb85f4 to your computer and use it in GitHub Desktop.
Save richarddd/b5b657729aaeecd3de86ef0cfccb85f4 to your computer and use it in GitHub Desktop.
Parse Bash Arguments
#!/bin/sh
set -e
usage_error () { echo >&2 "$(basename $0): $1"; exit 2; }
assert_argument () { test "$1" != "$EOL" || usage_error "$2 requires an argument"; }
if [ "$#" != 0 ]; then
EOL=$(echo '\01\03\03\07')
set -- "$@" "$EOL"
while [ "$1" != "$EOL" ]; do
opt="$1"; shift
case "$opt" in
# Your options go here.
-f|--flag) flag='true';;
-n|--name) assert_argument "$1" "$opt"; name="$1"; shift;;
# Arguments processing. You may remove any unneeded line after the 1st.
-|''|[!-]*) set -- "$@" "$opt";; # positional argument, rotate to the end
--*=*) set -- "${opt%%=*}" "${opt#*=}" "$@";; # convert '--name=arg' to '--name' 'arg'
-[!-]?*) set -- $(echo "${opt#-}" | sed 's/\(.\)/ -\1/g') "$@";; # convert '-abc' to '-a' '-b' '-c'
--) while [ "$1" != "$EOL" ]; do set -- "$@" "$1"; shift; done;; # process remaining arguments as positional
-*) usage_error "unknown option: '$opt'";; # catch misspelled options
*) usage_error "this should NEVER happen ($opt)";; # sanity test for previous patterns
esac
done
shift # $EOL
fi
# Do something cool with "$@"... \o/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment