getopt is a command used in scripts to parse their options and add a basic error checking ability.
getopt is not
getopts the bash built-in that has similiar functionality. Urban Vagabond explains:
getoptsare different beasts, and people seem to have a bit of misunderstanding of what they do.
getoptsis a built-in command to bash [that] processes command-line options in a loop and assigns each found option and value in turn to built-in variables [(so that they can be further processed)].
getopt, however, is an external utility program, and it doesn’t actually process your options for you the way that [(e.g.)] bash getopts, the Perl Getopt module, or the Python optparse/argparse modules do. All that
getoptdoes is canonicalize the options that are passed in — (i.e. convert them to a more standard form) so that it’s easier for a shell script to process them.
For example, a use of getopt converts the following:
tmpscript -abd -ooutfile.txt
tmpscript -a -b -d -o outfile.txt
getopt can also process the long format option of
--output=/tmp.... Also basic error check abilities, it has:
tmpscript -c tmpscript: invalid option -- 'c'
tmpscript -o tmpscript: option requires and argument -- 'o'
getopt gets defined by telling it the available options in short and long form (if you like). An option with a colon (:) following denotes that an argument is required for that option. If followed by two colons the argument is optional. Here is an example:
Options are generally set as variables so that they can defined how to be used after the while loop (usually, so that mainly they are processed in the right order).
getopt parses in the same order as specified on the input, so a
-a -d -b input would not work real well if the
-d option required the
-b option to run correctly.
One caveat of
getopt is that each option allows either one or no arguments to follow. So in input like
tmpscript -v --files file1.txt file2.txt file3.txt just isn’t possible in any type of predictable-fashion. One can however use quotes on the input:
tmpscript -v --files "file1.txt file2.txt"
or use mutiple options (
-f file1.txt -f file2.txt) and append them to an array, as seen, here.