ZetCode

Modula-2 command-line arguments

last modified November 27, 2026 Modula-2

ISO Modula-2 treats the command-line arguments as one more source of input. ProgramArgs.ArgChan returns a channel from which the current argument is read with the procedures of TextIO, IsArgPresent tells whether there is a current argument, and NextArg moves to the next one.

Listing the arguments

The first program reads every argument with TextIO.ReadString and prints it with its number.

args.mod
MODULE args;
FROM ProgramArgs IMPORT ArgChan, IsArgPresent, NextArg;
FROM TextIO IMPORT ReadString;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;

VAR
  arg: ARRAY [0..255] OF CHAR;
  i: CARDINAL;

BEGIN
  i := 0;
  WHILE IsArgPresent() DO
    ReadString(ArgChan(), arg);
    WriteCard(i, 0); WriteString(": [");
    WriteString(arg); WriteString("]"); WriteLn;
    INC(i);
    NextArg
  END
END args.

The loop runs while an argument is present. ReadString reads the current argument into arg, and NextArg makes the next one current. In gm2 the first argument, number 0, is the name of the program as it was typed. The shell splits the command line at spaces, so an argument with a space must be quoted, and '' passes an empty argument.

$ gm2 -fiso args.mod -o args
$ ./args one "two words" '' 3
0: [./args]
1: [one]
2: [two words]
3: []
4: [3]

Skipping the program name

Most programs do not need their own name, so they call NextArg once before they read anything.

greet.mod
MODULE greet;
FROM ProgramArgs IMPORT ArgChan, IsArgPresent, NextArg;
FROM TextIO IMPORT ReadString;
FROM STextIO IMPORT WriteString, WriteLn;

VAR
  name: ARRAY [0..63] OF CHAR;

BEGIN
  NextArg;
  IF NOT IsArgPresent() THEN
    WriteString("usage: greet name..."); WriteLn
  END;
  WHILE IsArgPresent() DO
    ReadString(ArgChan(), name);
    WriteString("Hello there, "); WriteString(name); WriteString("!");
    WriteLn;
    NextArg
  END
END greet.

After the first NextArg, the current argument is the first one the user typed. When there is none, the program prints a usage line, the customary short description of how to call it. Otherwise it greets each name in turn.

$ gm2 -fiso greet.mod -o greet
$ ./greet
usage: greet name...
$ ./greet Lucia Tomas
Hello there, Lucia!
Hello there, Tomas!

Numbers as arguments

Arguments are text, and numbers in them have to be converted. The program uses the Numbers module from the reading input article, whose ToInt accepts only valid whole numbers.

addup.mod
MODULE addup;
FROM ProgramArgs IMPORT ArgChan, IsArgPresent, NextArg;
FROM TextIO IMPORT ReadString;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM Numbers IMPORT ToInt;
IMPORT TextIO, StdChans, IOChan;

VAR
  arg: ARRAY [0..63] OF CHAR;
  n, sum: INTEGER;
  ok: BOOLEAN;

BEGIN
  sum := 0;
  ok := TRUE;
  NextArg;
  WHILE IsArgPresent() DO
    ReadString(ArgChan(), arg);
    IF ToInt(arg, n) THEN
      INC(sum, n)
    ELSE
      TextIO.WriteString(StdChans.StdErrChan(), "not a whole number: ");
      TextIO.WriteString(StdChans.StdErrChan(), arg);
      TextIO.WriteLn(StdChans.StdErrChan());
      IOChan.Flush(StdChans.StdErrChan());
      ok := FALSE
    END;
    NextArg
  END;
  IF ok THEN
    WriteString("sum: "); WriteInt(sum, 0); WriteLn
  END
END addup.

Every argument that is a whole number is added to the sum. The others are reported on standard error, and the sum is not printed, because a sum of the valid arguments alone would be misleading. Flushing the error channel after each message keeps the lines in order on the terminal, as described in the console output article. Numbers is compiled once and linked to the program.

$ gm2 -fiso -c Numbers.mod
$ gm2 -fiso addup.mod Numbers.o -o addup
$ ./addup 1 2 3 -4
sum: 2
$ ./addup 5 x 7 2.5
not a whole number: x
not a whole number: 2.5

Options

Options start with a dash and change what a program does. Some are flags on their own, others take a value from the next argument. The program prints its words, optionally in capitals and several times.

options.mod
MODULE options;
FROM ProgramArgs IMPORT ArgChan, IsArgPresent, NextArg;
FROM TextIO IMPORT ReadString;
FROM STextIO IMPORT WriteString, WriteLn;
FROM Strings IMPORT Equal, Capitalize;
FROM Numbers IMPORT ToInt;

VAR
  arg: ARRAY [0..63] OF CHAR;
  times, i: INTEGER;
  shout, ok: BOOLEAN;

BEGIN
  times := 1;
  shout := FALSE;
  ok := TRUE;
  NextArg;
  WHILE ok AND IsArgPresent() DO
    ReadString(ArgChan(), arg);
    NextArg;
    IF Equal(arg, "-u") THEN
      shout := TRUE
    ELSIF Equal(arg, "-n") AND IsArgPresent() THEN
      ReadString(ArgChan(), arg);
      NextArg;
      ok := ToInt(arg, times) AND (times > 0)
    ELSIF arg[0] = '-' THEN
      ok := FALSE
    ELSE
      IF shout THEN Capitalize(arg) END;
      FOR i := 1 TO times DO
        WriteString(arg); WriteLn
      END
    END
  END;
  IF NOT ok THEN
    WriteString("usage: options [-u] [-n count] word..."); WriteLn
  END
END options.

Each argument is read and NextArg is called at once, so the value of -n can be read right after it. Equal and Capitalize come from the ISO Strings module; Capitalize turns the letters of a string into capitals. The options apply to the words that follow them. An unknown option or a missing or invalid count ends the loop with a usage line.

$ gm2 -fiso options.mod Numbers.o -o options
$ ./options -n 2 hello -u there
hello
hello
THERE
THERE
$ ./options -x hello
usage: options [-u] [-n count] word...
$ ./options -n zero hi
usage: options [-u] [-n count] word...

Printing the first lines of files

The last program is a small tool in the style of head. It prints the first lines of each file named on the command line, three by default, or as many as the -n option says.

first.mod
MODULE first;
FROM ProgramArgs IMPORT ArgChan, IsArgPresent, NextArg;
FROM StreamFile IMPORT ChanId, Open, Close, OpenResults, read;
FROM TextIO IMPORT ReadString, SkipLine;
FROM IOResult IMPORT ReadResult, ReadResults;
FROM STextIO IMPORT WriteString, WriteLn;
FROM Strings IMPORT Equal, Length;
FROM Numbers IMPORT ToInt;

VAR
  arg: ARRAY [0..255] OF CHAR;
  count: INTEGER;
  files: CARDINAL;
  ok: BOOLEAN;

PROCEDURE Head(name: ARRAY OF CHAR; lines: INTEGER);
VAR
  cid: ChanId;
  res: OpenResults;
  line: ARRAY [0..255] OF CHAR;
BEGIN
  Open(cid, name, read, res);
  IF res # opened THEN
    WriteString("first: cannot open "); WriteString(name); WriteLn;
    RETURN
  END;
  WriteString("==> "); WriteString(name); WriteString(" <=="); WriteLn;
  WHILE lines > 0 DO
    ReadString(cid, line);
    IF (ReadResult(cid) = endOfInput) AND (Length(line) = 0) THEN
      lines := 0
    ELSE
      WriteString(line); WriteLn;
      SkipLine(cid);
      DEC(lines)
    END
  END;
  Close(cid)
END Head;

PROCEDURE GetArg(VAR s: ARRAY OF CHAR): BOOLEAN;
BEGIN
  IF NOT IsArgPresent() THEN RETURN FALSE END;
  ReadString(ArgChan(), s);
  NextArg;
  RETURN TRUE
END GetArg;

BEGIN
  count := 3;
  files := 0;
  NextArg;
  ok := GetArg(arg);
  IF ok AND Equal(arg, "-n") THEN
    ok := GetArg(arg) AND ToInt(arg, count) AND (count > 0);
    IF ok THEN ok := GetArg(arg) END
  END;
  WHILE ok DO
    Head(arg, count);
    INC(files);
    ok := GetArg(arg)
  END;
  IF files = 0 THEN
    WriteString("usage: first [-n lines] file..."); WriteLn
  END
END first.

GetArg reads the current argument and moves to the next one in one step, and returns FALSE when there are no more arguments. This keeps the main program short: an optional -n with its count, then one file name after another. Head opens a file with StreamFile and prints at most lines lines; a file that cannot be opened is reported, and the program goes on with the next one.

$ gm2 -fiso first.mod Numbers.o -o first
$ ./first -n 2 note.txt grades.csv
==> note.txt <==
Modula-2 came out of the Lilith project.
The workstation and its operating system
==> grades.csv <==
Agnes,72
Boris,45
$ ./first grades.csv missing.txt
==> grades.csv <==
Agnes,72
Boris,45
Clara,91
first: cannot open missing.txt
$ ./first -n x note.txt
usage: first [-n lines] file...

Source

The GNU Modula-2 manual

The ISO libraries in GNU Modula-2

In this article we have read the command-line arguments through the ProgramArgs channel, skipped the program name, converted numbers, parsed simple options and written a tool that prints the first lines of files. The environment and processes article reads environment variables and returns an exit status, and the files article covers the StreamFile procedures used in the last program.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Modula-2 tutorials.