plan9fox/sys/man/8/getflags
kvik ccf5d3fb9d aux/getflags: improve flagfmt parser
This makes the flagfmt parser more robust and accepting
a looser input language — namely by allowing whitespace
around specifier fields and ignoring any empty fields.

Long flagfmts can thus be pleasingly displayed:

	flagfmt='
		a, b, c, C:cache,
		m:mtpt mountpoint,
		s:srvn srvname'
2020-05-07 00:10:09 +02:00

108 lines
2.4 KiB
Text

.TH GETFLAGS 8
.SH NAME
getflags, usage \- command-line parsing for shell scripts
.SH SYNOPSIS
.B aux/getflags $*
.PP
.B aux/usage
.SH DESCRIPTION
.I Getflags
parses the flags in its command-line arguments
according to the environment variable
.BR $flagfmt .
This variable should be a comma-separated list of flag specifiers.
Each flag is a single letter, optionally followed by a
colon and a name. It may be followed by a space-separated
list of argument names.
.PP
.I Getflags
prints an
.IR rc (1)
script to be evaluated by the calling program.
For every flag specified in
.BR $flagfmt ,
the generated script sets a corresponding environment variable.
If the flag specifier contains
.BR :name ,
the corresponding variable is named
.BR $name .
Otherwise, it is named
.BI $flag x.
.PP
After evaluating the script, the environment variables will
be set as follows:
If a flag is not present in the argument list, the environment
variable will default to the empty list.
If the flag is present and takes no arguments, the environment
variable will be initialized with the string
.BR '1' .
If the flag takes arguments, the flag's variable will be initialized
with a list of those argument values.
The script then sets the variable
.B $*
to the list of remaining non-flag arguments.
.PP
The
.B $status
is variable to the empty string on success, or
.B 'usage'
when there is an error parsing the command line.
.PP
.I Usage
prints a usage message to standard error.
The message is constructed using
.BR $0 ,
.BR $flagfmt ,
and
.BR $args .
The program name is taken from
.BR $0 ,
as set by
.IR rc (1)
The list of flags is extracted from
.BR $flagfmt .
The description of positional argument list is taken from
.BR $args .
.SH EXAMPLE
.PP
An example of the script generated:
.IP
.EX
% flagfmt='e:example, x, a:arg with args'
% aux/getflags -exa arg list positional stuff
example=()
flagx=()
arg=()
example=1
flagx=1
arg=(arg list)
*=(positional stuff)
status=''
.EE
.PP
Parse the arguments for
.IR leak (1):
.IP
.EX
flagfmt='b:showbmp, s:acidfmt, f binary, r res, x width'
args='name | pid list'
if(! ifs=() eval `{aux/getflags $*} || ~ $#* 0){
aux/usage
exit usage
}
if(~ $#showbmp 0)
echo '-b flag not set'
echo $showbmp # named
echo $acidfmt # also named
echo $flagf # default name
echo $flagr # default name
.EE
.SH SOURCE
.B /sys/src/cmd/aux/getflags.c
.br
.B /sys/src/cmd/aux/usage.c
.SH SEE ALSO
.IR arg (2)