I remember having seen somewhere a bash
script using case
and shift
to walk through the list of positional parameters, parse flags and options with arguments when it encounters them, and removes them after parsing to leave only the bare arguments, which are later processed by the rest of the script.
For example, in parsing the command line of cp -R file1 -t /mybackup file2 -f
, it would first walk through the parameters, recognize that the user has requested to descend into directories by -R
, specified the target by -t /mybackup
and to force copying by -f
, and remove those from the list of parameters, leaving the program to process file1 file2
as the remaining arguments.
But I don't seem to be able to remember/find out whatever script I saw whenever. I'd just like to be able to do that. I have been googling around various sites and append a list of relevant pages I examined.
A question on this website specifically asked about "order-independent options" but both the single answer and the answer of the question it was dupped to does not consider cases like the above where the options are mixed with normal arguments, which I presume was the reason for the person to specifically mention order-independent options.
Since bash
's built-in getopts
seems to stop at the first non-option argument, it does not seem to be sufficient as a solution. This is why the Wooledge BashFAQ's page (see below) explains how to rearrange the arguments. But I'd like to avoid creating multiple arrays in case the argument list is quite long.
Since shift
does not support popping individual arguments off the middle of the parameter list, I am not sure what is a straightforward way to implement what I am asking.
I'd like to hear if anyone has any solutions to removing arguments from the middle of the parameter list without creating a whole new array.
Pages that I've already seen:
- http://mywiki.wooledge.org/ComplexOptionParsing#Rearranging_arguments
- http://mywiki.wooledge.org/BashFAQ/035
- Using getopts in bash shell script to get long and short command line options
- http://wiki.bash-hackers.org/scripting/posparams
- http://wiki.bash-hackers.org/howto/getopts_tutorial
- bash argument case for args in $@
- What is the canonical way to implement order independent options in bash scripts?
- How do I handle switches in a shell script?