ARG(2) ARG(2) NAME arg - parse program arguments SYNOPSIS include "arg.m"; arg := load Arg Arg->PATH; init: fn(argv: list of string); progname: fn(): string; opt: fn(): int; arg: fn(): string; argv: fn(): list of string; DESCRIPTION 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. Subse- quent calls to progname return it. Options are arguments containing one or more letters pre- ceded 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 pro- grams 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. The argument list remaining after the last call to opt is returned by argv. EXAMPLE The following Limbo program takes options b, c and f, where f takes a file name argument. Page 1 Plan 9 (printed 12/21/24) ARG(2) ARG(2) 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 := ""; arg->init(args); 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 a b c and when invoked by: ./prog -b -f file -z -- -bc the output is: unknown option (z) ./prog 1 0 file -bc Page 2 Plan 9 (printed 12/21/24) ARG(2) ARG(2) SOURCE /appl/lib/arg.b SEE ALSO sh(1), mash(1), command(2) Page 3 Plan 9 (printed 12/21/24)