O'Reilly logo

Learning the Korn Shell, 2nd Edition by Bill Rosenblatt, Arnold Robbins

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using getopts

The getopts command is extremely capable. With it, you can make your shell scripts accept long options, specify that arguments are optional or numeric, and provide descriptions of the arguments and values such that the -?, --man, --html and --nroff options work the same for your program as they do for the ksh93 built-in commands.

The price for this power is the complexity of the option description “language.” Based on a description provided by Dr. Glenn Fowler of AT&T Research, we describe how the facilities evolved, how they work, and summarize how to use them in your own programs. We use the the extended getopts command in the solution to Task B-1.

The first step is to describe the options. This is done with a comment at the top of the script:

# usage: phaser4 [ options ] files
#   -k, --kill                  use kill setting (default)
#   -l n, --level n             set phaser level (default = 2)
#   -s, --stun                  use stun-only setting
#   -t [lf], --tricorder [lf]   tricorder mode, opt. scan for life form lf

Now the fun begins. This outline of capabilities follows the order in which features were added to getopts.

  1. Start with the getopts command as described in Chapter 6. This yields a simple option string that only allows one-letter options:

    USAGE="kl#st:"
    while getopts "$USAGE" optchar ...

  2. Add a textual description for the option argument. This is done by ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required