In this lab, you will practice using getopts
in a toy
shell script to accept command line options.
The name of the shell script is optsargs
.
The options to support are:
-h
: If this occurs at least once, regardless of
other options and arguments, print this help message (to stdout), and
exit the script:
Options:
-h Print this help message.
-m MSG Add message.
-N NAME Set name.
-v Add Verbosity.
sample-help.txt has the exact help message.
-m MSG
: Save the message for later use below. If
there are multiple occurrences, concatenate all messages. If there is
none, the default is the empty string.
-N NAME
: Save the name for later use below. If there
are multiple occurrences, save only one name, whichever is simpler. If
there is none, the default is “nobody
” (without the
quotes).
-v
: Count how many times this occurs for
below.
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:
v=COUNT
where COUNT
is how many times
-v
was seen.
N='NAME'
where NAME
is the name from
-N
above. Note: We add single quotes around the
name.
For each non-option argument ARG
, output one
line
ARG:MSGS
where MSGS
is the concatenation of messages from
-m
above.
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'
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.)