Skip to content

Instantly share code, notes, and snippets.

@jstine35
Last active September 25, 2024 11:03
Show Gist options
  • Save jstine35/0d49e3b3b9343c3bb1f490946479393d to your computer and use it in GitHub Desktop.
Save jstine35/0d49e3b3b9343c3bb1f490946479393d to your computer and use it in GitHub Desktop.
Bash Positional Option Parsing with rvalue assignment
#!/bin/bash
#
# Uses lazy for-loop instead of the while construct, which is made possible by assuming ONLY the
# modern POSIX CLI switch assignments, eg. --lvalue=rvalue
#
# No consideration for shorthand switches is made here. This idiom is most commonly used for rapid
# internal tool development where longhand switches are preferred.
POSITIONAL=( )
for item; do
rvalue="${item#*=}"
[[ "$item" == --help ]] && SHOWHELP=1 && continue
[[ "$item" == --force ]] && FORCE=1 && continue
[[ "$item" == --force=* ]] && FORCE=$rvalue && continue
[[ "$item" == --* ]] && {
>&2 echo "unrecognized option: $item"
CLI_ERROR=1
continue
}
POSITIONAL+=( "$item" )
done
set -- "${POSITIONAL[@]}"
if (( SHOWHELP )); then
echo ""
exit 0
fi
(( CLI_ERROR )) && exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment