I'm writing a large number of Bash functions that are to be capable of acquiring different pieces of information from the command line passed using positional arguments or named arguments (provided by getopts
). The idea is that positional arguments are to be used largely for briskness and direct human control while named arguments are to be used largely for clarity and control by other functions. To illustrate how I am thinking about this, consider a function that can convert from one thing to another. This function can be used, broadly speaking, in a quick mode or in an advanced mode. In the quick mode, few arguments are specified and, generally, are positional arguments, while in the advanced mode, many arguments can be specified and, generally, are named arguments. For examples...
quick mode
This mode can be used in a manner such as the following:
function fileName1 fileName2
It converts one file to another using internal assumptions and measurements made autonomously.
advanced mode
This mode can be used in a manner such as the following:
function -i fileName1 -o fileName2 -m -r 100 -v
This mode can be used also in a manner such as the following:
function -m -v fileName1 fileName2 -r 100
Note that -v
accepts no argument. It is an option only (specifying something such as verbosity).
So, the logic in this case would be that the first positional argument is assumed to be fileName1
and the second positional argument is assumed to be fileName2
unless either of these file names are specified using the -i
or -o
options, in which case they are used because they are given higher priority (and the first and second positional arguments are ignored).
I ask for suggestions and guidance in implementing these types of requirements in as general a way as possible because this approach is to be applied to a library of over 150 functions.
Be aware that if you use
getopts
, all positional arguments must come after any options. A second caveat is that if you usegetopts
to parse arguments to a function, you must reset the globalOPTIND
variable to 1 after parsing any options. Otherwise I think the solution is straightforward:argparse.sh
Output