B09 Lab Week 4

In this lab, you will practice using getopts in a toy shell script to accept command line options.

Specification

The name of the shell script is optsargs.

The options to support are:

If there is an unrecognized options, regardless of other options and arguments, let getopts print its error message to stderr, and exit with exit code 1.

Except for the early exit conditions above, the shell script outputs (to stdout) these lines:

  1. v=COUNT where COUNT is how many times -v was seen.

  2. N='NAME' where NAME is the name from -N above. Note: We add single quotes around the name.

  3. For each non-option argument ARG, output one line

    ARG:MSGS

    where MSGS is the concatenation of messages from -m above.

Samples

Sample 1 (sample-1.txt):

$ sh optsargs -m "hello world" -v -mwelcome -v foo bar
v=2
N='nobody'
foo:hello worldwelcome
bar:hello worldwelcome

Sample 2 (sample-2.txt):

$ sh optsargs -N "Lydia Deetz"
v=0
N='Lydia Deetz'

Appendix: Motivation

This toy exercise covers most ways of how most programs support options.

-h is pretty standard for printing a help message and exiting, even when there are other arguments to the command.

Some options are like -m MSG, where the user can provide many, and the program promises to combine them in a suitable way. (In this exercise, we just concatenate, but you can see how to generalize.)

Some options are like -N NAME, where only one is expected, and if the user provides many, the programmer is nice to allow it (or too lazy to write extra code to detect and ban it ☺), but only one can be honoured. Some programs honour the first, some others the last.

-v is pretty standard for turning on verbosity (the program prints more messages about what it is doing); moreover, some programs support multiple levels of verbosity, and the user requests more by adding more -v’s. (In this exercise, we just count, but you can see that in reality you can act upon the count appropriately.)