I wrote a library function which processes an argument list and allows for easy querying of options, etc. (The full source is here, but I hope it shouldn't be necessary to read through the details for this particular question.)
Essentially you pass in a list of args, usually "$@", to a function, and any other non-option arguments (positionals) get passed on to another list called BB_POSARGS.
To make it easier for the programmer using the library, I generally suggest overwriting the argument list after parsing as follows: set -- "${BB_POSARGS[@]}".
bb_parseargs "$@" # here $@ are the original arguments
set -- "${BB_POSARGS[@]}" # now $@ only contains positional arguments
unset BB_POSARGS # clean up
# Check options, flags, etc. with bb_getopt, bb_checkopt
for things in "$@"; do
# this won't contain any options, flags, etc.
echo "doing something with $thing"
done
Ideally I could replace this boilerplate:
bb_parseargs "$@" # here $@ are the original arguments
set -- "${BB_POSARGS[@]}" # now $@ only contains positional arguments
unset BB_POSARGS # clean up
with one function, alias, macro, etc. named bb_processargs:
bb_processargs # parses $@; afterward, $@ only contains positional arguments
I don't think bb_processargs can be a function because using set -- within a function only changes its own argument list, not its calling parent's.
Aliases don't seem to support arguments or propagate the "$@".
Is there any way to bundle the set -- with the function call?
CodePudding user response:
Why can't you just define the QOL function as an alias, something like this:
bash-5.1$ alias my_thing='echo $@;set -- a b c'
bash-5.1$ set -- 1 2 3
bash-5.1$ my_thing
1 2 3
bash-5.1$ my_thing
a b c
See how my_thing uses $@ and then sets the new argument list, in your case you would use something like:
alias bb_processargs='bb_parseargs "$@";set -- "${BB_POSARGS[@]}";unset BB_POSARGS'
