[manual index][section index]


arg - parse program arguments


include "arg.m";
arg := load Arg Arg->PATH;

init:     fn(argv: list of string);
setusage: fn(s: string);
usage:    fn();
progname: fn(): string;
opt:      fn(): int;
arg:      fn(): string;
earg:     fn(): string;
argv:     fn(): list of string;


Arg parses a program's argument list in a traditional form, as received from a shell or other program (see command(2)). The list must be passed to init to set the state for the other functions.

Arg takes the first argument to be the program name. Subsequent calls to progname return it.

Options are arguments containing one or more letters preceded by - (dash, hyphen, minus). The list of options ends before the first argument that does not begin with a -. Option lists also end after an argument --, to allow programs to accept arguments that would otherwise look like options (eg, file names for rm(1) or a pattern for grep(1)). Finally, option lists end before an argument -, which is traditionally interpreted by some commands as referring to the standard input or output (depending on context).

Successive calls to opt return option characters in turn; 0 is returned at the end of the list. A program might take a parameter to a given option (eg, an option of the form -ffile or -f file). Following a call to opt, a call to arg will return the rest of the current argument string if not empty, failing that, the next argument string if any, and otherwise nil. Earg is like arg except that if there is no argument associated with the option, an error message is printed to standard error, and a "fail:usage" exception raised. Setusage sets the error message that will be printed in this case (preceded by `usage:' and followed by a newline).

The argument list remaining after the last call to opt is returned by argv.


The following Limbo program takes options b, c and f, where f takes a file name argument.

implement Prog;
include "sys.m";
    sys: Sys;
include "draw.m";
include "arg.m";
    arg: Arg;
Prog: module
    init: fn(nil: ref Draw->Context, nil: list of string);

init(nil: ref Draw->Context, args: list of string)
    sys = load Sys Sys->PATH;
    arg = load Arg Arg->PATH;

    bflag := cflag := 0;
    file := "";
    while((c := arg->opt()) != 0)
        case c {
        'b' => bflag = 1;
        'c' => cflag = 1;
        'f' => file = arg->arg();
        * =>   sys->print("unknown option (%c)\n", c);
    args = arg->argv();
    sys->print("%s %d %d %s\n", arg->progname(), bflag, cflag, file);
    for(; args != nil; args = tl args)
        sys->print("%s\n", hd args);

When invoked as follows:

prog -bc -ffile a b c

the output is:

prog 1 1 file

and when invoked by:

./prog -b -f file -z -- -bc

the output is:

unknown option (z)
./prog 1 0 file




sh(1), mash(1), command(2)

ARG(2 ) Rev:  Tue Mar 31 02:42:39 GMT 2015