Last active
September 25, 2024 11:03
-
-
Save jstine35/0d49e3b3b9343c3bb1f490946479393d to your computer and use it in GitHub Desktop.
Bash Positional Option Parsing with rvalue assignment
This file contains hidden or 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 | |
# | |
# 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