ZetCode

Command-line arguments in Pascal

last modified November 18, 2026 Free Pascal 3.2.2

A command-line program receives its arguments as strings, already split by the shell. Pascal exposes them through two standard functions: ParamCount returns how many arguments were given, and ParamStr(N) returns the N-th one. The program name itself is ParamStr(0) and is not counted. This article reads the arguments, shows how quoting preserves spaces, validates numbers with TryStrToInt, parses long options, prints usage messages, and returns meaningful exit codes.

ParamCount and ParamStr

The arguments are numbered from 1 to ParamCount, and ParamStr(N) returns the N-th argument as a string. Index 0 holds the program name, which may be an absolute path, a relative path, or just the name that was typed, depending on how the program was started. The example prints the program name, the count, and every argument in brackets so that empty values and spaces are visible.

args.pas
program args;
{$mode objfpc}{$H+}

var
  I: Integer;

begin
  WriteLn('program: ', ParamStr(0));
  WriteLn('count: ', ParamCount);
  for I := 1 to ParamCount do
    WriteLn(I, ': [', ParamStr(I), ']');
end.

Running the program with three arguments prints three lines. The third argument contains a space, but the shell passed it as one string because it was quoted; the Pascal program never sees the quotes. ParamStr(0) is a full path in this run because the program was started as ./args from its own directory and the RTL expanded it.

An empty argument is still an argument. The second run below passes one empty string, so ParamCount is 1 and the bracket line is empty. This distinction matters for programs that treat an empty value as "not supplied": ParamCount is the only reliable way to tell the two cases apart.

$ fpc -gl args.pas
$ ./args alpha beta "two words"
program: /tmp/opencode/pas-work/a35/args
count: 3
1: [alpha]
2: [beta]
3: [two words]
$ ./args ""
program: /tmp/opencode/pas-work/a35/args
count: 1
1: []

Validating numeric arguments

Arguments arrive as strings, and converting them with StrToInt raises an exception when the text is not a valid integer. TryStrToInt returns a Boolean and stores the value through an output parameter, which makes it suitable for input that a user typed. The program below sums its arguments and stops with a usage message when there are none, or with an error when one argument is not a number.

sumargs.pas
program sumargs;
{$mode objfpc}{$H+}

uses SysUtils;

var
  I, Value, Sum: Integer;

begin
  if ParamCount = 0 then
  begin
    WriteLn('usage: sumargs N1 N2 ...');
    Halt(2);
  end;

  Sum := 0;
  for I := 1 to ParamCount do
  begin
    if not TryStrToInt(ParamStr(I), Value) then
    begin
      WriteLn('not a number: ', ParamStr(I));
      Halt(1);
    end;
    Inc(Sum, Value);
  end;
  WriteLn('sum: ', Sum);
end.

Halt(N) terminates the program immediately and sets the exit status to N, so the shell can tell success from a usage error and from invalid input. A negative number such as -5 is accepted by TryStrToInt, so a leading minus sign is not mistaken for an option. The sum is an Integer; a larger accumulator or an overflow check would be needed for long argument lists.

$ ./sumargs 10 20 12
sum: 42
$ echo $?
0
$ ./sumargs 10 x 12
not a number: x
$ echo $?
1
$ ./sumargs
usage: sumargs N1 N2 ...
$ echo $?
2

Parsing long options

A common convention writes options as --name=value or --flag, and everything else is a positional argument. The parser below scans the arguments once, splits an option at the first =, converts the value of --count, and records --upper as a Boolean flag. Unknown options stop the program instead of being silently ignored.

options.pas
program options;
{$mode objfpc}{$H+}

uses SysUtils;

var
  I, P, Count: Integer;
  Arg, Key, Value, FileName: string;
  Upper: Boolean;

begin
  Count := 1;
  Upper := False;
  FileName := '';

  for I := 1 to ParamCount do
  begin
    Arg := ParamStr(I);
    if Copy(Arg, 1, 2) = '--' then
    begin
      P := Pos('=', Arg);
      if P > 0 then
      begin
        Key := Copy(Arg, 3, P - 3);
        Value := Copy(Arg, P + 1, MaxInt);
        if Key = 'count' then
        begin
          if not TryStrToInt(Value, Count) then
          begin
            WriteLn('bad value for --count: ', Value);
            Halt(1);
          end;
        end
        else
        begin
          WriteLn('unknown option: --', Key);
          Halt(1);
        end;
      end
      else
      begin
        Key := Copy(Arg, 3, MaxInt);
        if Key = 'upper' then
          Upper := True
        else
        begin
          WriteLn('unknown option: --', Key);
          Halt(1);
        end;
      end;
    end
    else
      FileName := Arg;
  end;

  WriteLn('count: ', Count);
  WriteLn('upper: ', Upper);
  WriteLn('file: [', FileName, ']');
end.

Copy(Arg, 3, P - 3) extracts the key between the two dashes and the equals sign, and Copy(Arg, P + 1, MaxInt) takes everything after the equals sign; asking for more characters than remain is safe and returns the rest of the string. The flag branch uses Key = 'upper' after the same prefix test. Only long options are handled here; a real parser would also accept -c 3, --count 3, and a -- marker that ends option processing.

$ ./options --count=3 --upper notes.txt
count: 3
upper: TRUE
file: [notes.txt]
$ ./options --count=x
bad value for --count: x
$ echo $?
1
$ ./options --bad
unknown option: --bad
$ echo $?
1

Exit status

The exit status is a small integer that the shell reads as $?. By convention 0 means success, 1 means a general failure, and 2 means a usage error. Halt(N) sets the status immediately, while ExitCode := N sets it for the normal end of the program. The assignment only has an effect when SysUtils is in the uses clause, and Exit ends the main block cleanly.

status.pas
program status;
{$mode objfpc}{$H+}

uses SysUtils;

begin
  if ParamCount <> 1 then
  begin
    WriteLn('usage: status FILE');
    ExitCode := 2;
    Exit;
  end;

  WriteLn('checking ', ParamStr(1));
  ExitCode := 0;
end.

The program accepts exactly one positional argument. With none, or with two, it prints the usage line and returns 2; with one it returns 0. The environment and processes article shows how a parent program reads the status of a child, and the exceptions article explains why an unhandled exception normally ends the process with status 217.

$ ./status
usage: status FILE
$ echo $?
2
$ ./status data.txt
checking data.txt
$ echo $?
0
$ ./status one two
usage: status FILE
$ echo $?
2

Next steps

Arguments often name files or configure a run, so the reading input article describes reading from standard input and from files, and the environment and processes article explains where the program lives and how it starts other programs. The exceptions article covers the errors that a parser can raise, and the procedural types article shows how to build an option table with one handler per option.

Source

Free Pascal: ParamCount

Free Pascal: ParamStr

Free Pascal: Halt

In this article we read the argument list, preserved spaces and empty strings, validated numbers, parsed long options, printed usage messages, and returned exit codes. The series continues with environment and processes in Pascal.

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 Pascal tutorials.