Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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))
@adamhotep

This comment has been minimized.

Copy link
Owner Author

commented Apr 16, 2016

This is a refinement of the suboptimal code at https://stackoverflow.com/a/5255468/519360
See also my own code to support long options in POSIX shell at https://stackoverflow.com/a/28466267/519360

That second link supports arguments in the form --foo=bar while the code here supports arguments in the form --foo bar. It wouldn't be hard to adapt this code to support both while my preferred method (which only has one loop) would need to get rather ugly to do it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.