- So far, we have just been processing every argument to our
scripts, but our scripts should work like other UNIX commands and
allow options.
- Using getopts lets you process options properly without having
to write all the logic.
- As an example, when using options that take no arguments
the options can be separate, strung together (sometimes called "stacking"
them together), and be in any order.
For instance, all of these commands should do exactly the same thing:
ls -l -r -t
ls -lrt
ls -r -l -t
ls -trl
- Using getopts will also enforce options that require a parameter,
for instance like the -f option for the cut command:
cut -f 1
The -f flag requires an argument (in this case the field number).
If it is missing, getopts will handle it as an error.
- It will also handle the fact that a space between the option and its
argument is optional and allows each of the following to mean the same thing:
sort -u -o outfile file1
sort -o outfile -u file1
sort -uo outfile file1
sort -uooutfile file1
- Using getopt means that you scripts can process arguments just like
(most) other UNIX commands.
- So, although it may seem a little convoluted at first, once you get the
hang of it, getopts is a handy way to process options in your shell scripts.
- Run man getopts - what does it tell you?
- Small getopts tutorial from Bash Hackers Wiki