Bash: Why is used eval and shift in a script that parses command line arguments?
One of the many things that getopt
does while parsing options is to rearrange the arguments, so that non-option arguments come last, and combined short options are split up. From man getopt
:
Output is generated for each element described in the previous section.
Output is done in the same order as the elements are specified in the
input, except for non-option parameters. Output can be done in
compatible (unquoted) mode, or in such way that whitespace and other
special characters within arguments and non-option parameters are
preserved (see QUOTING). When the output is processed in the shell
script, it will seem to be composed of distinct elements that can be
processed one by one (by using the shift command in most shell
languages).
[...]
Normally, no non-option parameters output is generated until all
options and their arguments have been generated. Then '--' is
generated as a single parameter, and after it the non-option parameters
in the order they were found, each as a separate parameter.
This effect is reflected in your code, where the option-handling loop assumes that all option arguments (including arguments to options) come first, and come separately, and are finally followed by non-option arguments.
So, TEMP
contains the rearranged, quoted, split-up options, and using eval set
makes them script arguments.
As for shift
, it does what it always does: remove the first argument, and shift all arguments (so that what was $2
will now be $1
). This eliminates the arguments that have been processed, so that, after this loop, only non-option arguments are left and you can conveniently use $@
without worrying about options.