Skip to content

Instantly share code, notes, and snippets.

@brentmcconnell
Forked from adamhotep/longopts2getopts.sh
Created October 25, 2019 18:47
Show Gist options
  • Save brentmcconnell/fb648b3debbd76632fa85514c25119f0 to your computer and use it in GitHub Desktop.
Save brentmcconnell/fb648b3debbd76632fa85514c25119f0 to your computer and use it in GitHub Desktop.
POSIX shell: support long options by converting them to short options
# a refinement of https://stackoverflow.com/a/5255468/519360
# see also my non-translating version at https://stackoverflow.com/a/28466267/519360
# translate long options to short
reset=true
for arg in "$@"
do
if [ -n "$reset" ]; then
unset reset
set -- # this resets the "$@" array so we can rebuild it
fi
case "$arg" in
--help) set -- "$@" -h ;;
--verbose) set -- "$@" -v ;;
--config) set -- "$@" -c ;;
# pass through anything else
*) set -- "$@" "$arg" ;;
esac
done
# now we can process with getopt
while getopts ":hvc:" opt; do
case $opt in
h) usage ;;
v) VERBOSE=true ;;
c) source $OPTARG ;;
\?) usage ;;
:)
echo "option -$OPTARG requires an argument"
usage
;;
esac
done
shift $((OPTIND-1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment