getoptions icon indicating copy to clipboard operation
getoptions copied to clipboard

Support for positional arguments

Open cweagans opened this issue 5 months ago • 5 comments

I have a command that can be invoked like so:

my_command --foo=bar "first_arg" "second_arg"

(first_arg and second_arg are arbitrary strings)

My parser definition looks like this:

parser_definition() {
  setup ARGS
  param FOO --foo
}
eval "$(getoptions parser_definition __parse) exit 1"
__parse "$@"

echo "$FOO"

That all works great, but then I need to do something like this for the remaining positional arguments:

parse_args() {
  local var_names=("$@")
  local i=0
  for arg in $ARGS; do
    echo export ${var_names[$i]}="$arg"
    i=$((i + 1))
  done
}

eval "$(parse_args "FIRST" "SECOND")"

echo $FIRST         # outputs "first_arg"
echo $SECOND    # outputs "second_arg"

Do you think it makes sense to add a new kind of argument to the parser_definition where I can define the positional arguments too? Maybe something along these lines:

parser_definition() {
  setup ARGS
  param FOO --foo
  arg MY_ARG
  arg ANOTHER_ARG
}

I imagine that this could filter $@ to elements that do not begin with a - or --, and then $MY_ARG is assigned the value of the first arg, $ANOTHER_ARG is assigned the value of the second arg, and so forth.

There are probably other considerations for this library, but as a starting point, does this idea make sense and/or would you be interested in a PR to add something like that?

cweagans avatar Sep 17 '24 02:09 cweagans