Blue42
Blue42

Reputation: 139

Code explanation required for a kornshell scripting novice

I know java so the do while and case are no issue. I have read the man page for getopts. It has been of some use. Really im looking for plain english explanation of what is happening with "getopts :d:p:nil optname"

while getopts :d:p:nil optname
do
 case $optname in

Upvotes: 0

Views: 100

Answers (2)

user1019830
user1019830

Reputation:

There should be some useful information in help getopts:

getopts: getopts optstring name [arg]

Parse option arguments.

Getopts is used by shell procedures to parse positional parameters as options.

OPTSTRING contains the option letters to be recognized; if a letter is followed by a colon, the option is expected to have an argument, which should be separated from it by white space.

Each time it is invoked, getopts will place the next option in the shell variable $name, initializing name if it does not exist, and the index of the next argument to be processed into the shell variable OPTIND. OPTIND is initialized to 1 each time the shell or a shell script is invoked. When an option requires an argument, getopts places that argument into the shell variable OPTARG.

...

Here OPTSTRING is the sequence :d:p:nil and name is called optname. The case statement will match against each different option while they are placed in optstring.

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 754700

The shell script is invoked with a collection of arguments, like any other command on Unix.

The getopts built-in command helps parse those arguments, dividing them up into:

  • Flags with no value associated with them
  • Flags with a value associated with them
  • Non-flag arguments (usually but not necessarily file names)

Given the loop:

while getopts :d:p:nil optname

the flags with no value associated with them are -n, -i and -l. The flags which need a value are -d and -p. The loop processes each of the flag arguments in the command line in turn. The single letter for the option is stored in the shell variable $optname. If the flag takes a value, then that is in $OPTARG.

The leading colon to the string defining the options says that getopts should not report errors, leaving that up to the script.

The getopts command returns success (0) when there was an option found; it returns failure (non-zero, probably 1) when there are no more options to process.

This can be because it came across an argument that didn't start with a dash, or because it came across the special marker argument --.

See also the getopt() function in C programming. The facilities of the shell are based on that.

There are extensions of various sorts to handle multi-letter option names. See also Using getopts in bash shell script to get long and short command line options.

Upvotes: 3

Related Questions