I have a script with this usage:
myscript [options] positional-args... -- [fwd-params]
Because [options]
can have long, or short variants, I like using getopt
. But I'm having troubles.
I use getopt
like this:
args=$(getopt -o a:,b --long alpha:,gamma -- "$@")
eval set -- "$args"
while : ; do
case "$1" in
-a | --alpha) a="$2" ; shift 2 ;;
-b ) b=true ; shift ;;
--gamma ) g=true ; shift ;;
-- ) shift ; break ;;
esac
done
positionals=()
while [ $# -gt 0 ] ; do
case "$1" in
* ) positionals+=("$1"); shift ;;
-- ) shift ; break ;;
esac
done
# What-ever is left in "$@" needs to be forwarded to another program
backend "$@"
This works great if I don't have any [fwd-params]
:
$ getopt -o a:,b -- -a 1 -b pos1 pos2
-a '1' -b -- 'pos1' 'pos2'
^-- getopt adds this to help me find
the end-of-options/start-of-positionals
But it falls apart if the user defined any [fwd-params]
. Here's my desired output:
$ getopt -o a:,b -- -a 1 -b pos1 pos2 -- fwd1
-a '1' -b -- 'pos1' 'pos2' '--' 'fwd1'
^
\- I'll use this to delimit
the positional arguments
from the forwarding ones.
And here's what I actually get. The user's intentional --
has been filtered out.
$ getopt -o a:,b -- -a 1 -b pos1 pos2 -- fwd1
-a '1' -b -- 'pos1' 'pos2' 'fwd1'
What's the best way to delimit my positional-arguments from the forwarding ones?
Asked by Stewart
(15631 rep)
May 28, 2024, 03:40 PM
Last activity: May 28, 2024, 04:36 PM
Last activity: May 28, 2024, 04:36 PM