Command-line arguments

suggest change

Command-line arguments are the main way to tell a command-line program what to do: which files to process, which mode to run in, where to write output. In Dart they arrive as a List<String> passed to main.

For anything beyond one or two arguments, use the args package, maintained by the Dart team. It's what dart, pub and most Dart tools use. It handles flags, options with values, defaults, allowed values, generated help text and sub-commands like git commit.

This article covers:

The examples were run with Dart 3.13 and args 2.7.0 on Windows. Shell commands use bash syntax unless noted.

Arguments in main

The arguments are the parameter of main. The name of the program is not included, unlike argv[0] in C:

import 'dart:io';

void main(List<String> args) {
  print('args: $args (${args.length})');
  for (final (i, a) in args.indexed) {
    print('  [$i] "$a"');
  }
  print('script: ${Platform.script.pathSegments.last}');
  // VM options given before the script name, minus two internal ones.
  final vmFlags = Platform.executableArguments
      .where((f) => !f.contains('executable_name='))
      .toList();
  print('VM flags: $vmFlags');
}

Output:

$ dart run bin/raw.dart hello "two words" --verbose -n=3 '' '*.dart'
args: [hello, two words, --verbose, -n=3, , *.dart] (6)
  [0] "hello"
  [1] "two words"
  [2] "--verbose"
  [3] "-n=3"
  [4] ""
  [5] "*.dart"
script: raw.dart
VM flags: []

Things to notice:

Options given to the Dart VM go before the script name and are not part of args. They're available in Platform.executableArguments:

$ dart --enable-asserts bin/raw.dart --enable-asserts b
args: [--enable-asserts, b] (2)
  [0] "--enable-asserts"
  [1] "b"
script: raw.dart
VM flags: [--enable-asserts]

The program filters out two internal --executable_name entries that the dart launcher adds on Windows.

Shells, quoting and wildcards

What your program receives depends on the shell that started it. In bash, zsh and Git Bash, the shell expands wildcards before the program starts:

$ dart bin/raw.dart *.yaml
args: [analysis_options.yaml, pubspec.yaml] (2)
  [0] "analysis_options.yaml"
  [1] "pubspec.yaml"
...

PowerShell and cmd.exe don't expand wildcards for native programs, and Dart doesn't do it either, so the pattern arrives as is. Quoting rules also differ: cmd.exe only understands double quotes, so single quotes stay in the argument:

# PowerShell
PS> dart bin/raw.dart *.yaml "two words" 'it''s'
args: [*.yaml, two words, it's] (3)

# cmd.exe
C:\> dart bin/raw.dart *.yaml "two words" 'single'
args: [*.yaml, two words, 'single'] (3)

If your program accepts file patterns and must work on Windows, expand them yourself, for example with the glob package, or list a directory with Directory.list and filter the names.

When you start a program from Dart with Process.run or Process.start, there's no shell by default: each list element is passed as exactly one argument, so there's no need for quoting. See Running OS commands.

Parsing by hand

For a small script, a loop with a switch works. Here's a parser for -v, -n <count>, --count=<count>, file names, and -- to end option parsing:

import 'dart:io';

void main(List<String> args) {
  var verbose = false;
  var count = 1;
  final files = <String>[];

  for (var i = 0; i < args.length; i++) {
    final arg = args[i];
    switch (arg) {
      case '-v' || '--verbose':
        verbose = true;
      case '-n' || '--count':
        if (i + 1 >= args.length) usage('$arg needs a value');
        count = int.tryParse(args[++i]) ?? usage('bad number: ${args[i]}');
      case _ when arg.startsWith('--count='):
        final v = arg.substring('--count='.length);
        count = int.tryParse(v) ?? usage('bad number: $v');
      case '--':
        files.addAll(args.skip(i + 1));
        i = args.length;
      case _ when arg.startsWith('-'):
        usage('unknown option: $arg');
      default:
        files.add(arg);
    }
  }
  print('verbose=$verbose count=$count files=$files');
}

Never usage(String error) {
  stderr.writeln('error: $error');
  stderr.writeln('usage: manual [-v] [-n <count>] <file>...');
  exit(64);
}

Output:

$ dart bin/manual.dart -v a.txt --count=3 b.txt
verbose=true count=3 files=[a.txt, b.txt]
$ dart bin/manual.dart -n 2 -- -weird.txt
verbose=false count=2 files=[-weird.txt]
$ dart bin/manual.dart -n x
error: bad number: x
usage: manual [-v] [-n <count>] <file>...
$ echo $?
64
$ dart bin/manual.dart -vn 2
error: unknown option: -vn
usage: manual [-v] [-n <count>] <file>...

Because usage returns Never, it can be used in expressions like ?? usage(...): the compiler knows it doesn't return.

That's already a lot of code, and it still doesn't support -n3, combined flags like -vn 2, --no-verbose, or a help screen that stays in sync with the code. That's what package:args is for.

The args package

Add it to your project:

dart pub add args

An ArgParser defines the accepted arguments, and parse returns an ArgResults:

import 'package:args/args.dart';

void main(List<String> args) {
  final parser = ArgParser()
    ..addFlag('verbose', abbr: 'v', help: 'Print more output.')
    ..addOption('count', abbr: 'n', defaultsTo: '1', help: 'How many times.')
    ..addOption('output', abbr: 'o', help: 'Write to this file.')
    ..addMultiOption('tag', abbr: 't', help: 'Add a tag (repeatable).');

  final results = parser.parse(args);

  print('verbose: ${results.flag('verbose')}');
  print('count:   ${results.option('count')}');
  print('output:  ${results.option('output')}');
  print('tags:    ${results.multiOption('tag')}');
  print('rest:    ${results.rest}');
  print('given:   ${results.options.where(results.wasParsed).toList()}');
}

There are three kinds of arguments:

Everything that isn't an option ends up in rest, in order. Output:

$ dart bin/basic.dart a.txt -v --count 5 -t x -ty --tag=z,w b.txt
verbose: true
count:   5
output:  null
tags:    [x, y, z, w]
rest:    [a.txt, b.txt]
given:   [verbose, count, tag]
$ dart bin/basic.dart -n3 -oout.txt in.txt
verbose: false
count:   3
output:  out.txt
tags:    []
rest:    [in.txt]
given:   [count, output]
$ dart bin/basic.dart -v -- -n 7
verbose: true
count:   1
output:  null
tags:    []
rest:    [-n, 7]
given:   [verbose]

The parser accepts all the common spellings of an option value: --count 5, --count=5, -n 5 and -n5. A few details:

Short flags can be combined (-vi), but an abbreviation that takes a value can't follow them: -vn3 fails with Option "-n" must be a flag to be in a collapsed "-". Write -v -n3 instead.

Help text, allowed values and errors

A real program needs --help, --version, validation and good error messages. This one is the skeleton of a grep-like tool:

import 'dart:io';

import 'package:args/args.dart';

const version = '1.2.0';

ArgParser buildParser() => ArgParser()
  ..addFlag('help', abbr: 'h', negatable: false, help: 'Show this help.')
  ..addFlag('version', negatable: false, help: 'Print the version.')
  ..addFlag('ignore-case', abbr: 'i', help: 'Case-insensitive matching.')
  ..addFlag('line-numbers',
      defaultsTo: true, help: 'Prefix matches with line numbers.')
  ..addOption('max-count',
      abbr: 'm', valueHelp: 'n', help: 'Stop after <n> matches per file.')
  ..addOption('color',
      allowed: ['auto', 'always', 'never'],
      defaultsTo: 'auto',
      allowedHelp: {
        'auto': 'Color only when writing to a terminal.',
        'always': 'Always use ANSI colors.',
        'never': 'Plain output.',
      },
      help: 'When to use colors.')
  ..addMultiOption('exclude',
      valueHelp: 'glob', splitCommas: false, help: 'Skip matching files.')
  ..addOption('log-file', aliases: ['logfile'], help: 'Write a debug log.')
  ..addFlag('trace', hide: true, help: 'Internal debugging.');

void printUsage(ArgParser parser, IOSink out) {
  out.writeln('Usage: search [options] <pattern> [<file>...]');
  out.writeln();
  out.writeln(parser.usage);
}

int run(List<String> args) {
  final parser = buildParser();
  final ArgResults results;
  try {
    results = parser.parse(args);
  } on FormatException catch (e) {
    stderr.writeln('search: ${e.message}');
    stderr.writeln('Run "search --help" for usage.');
    return 64; // EX_USAGE
  }

  if (results.flag('help')) {
    printUsage(parser, stdout);
    return 0;
  }
  if (results.flag('version')) {
    print('search $version');
    return 0;
  }

  final maxText = results.option('max-count');
  final maxCount = maxText == null ? null : int.tryParse(maxText);
  if (maxText != null && (maxCount == null || maxCount < 1)) {
    stderr.writeln('search: --max-count must be a positive integer, '
        'got "$maxText"');
    return 64;
  }

  if (results.rest.isEmpty) {
    stderr.writeln('search: missing <pattern>');
    printUsage(parser, stderr);
    return 64;
  }
  final pattern = results.rest.first;
  final files = results.rest.skip(1).toList();

  print('pattern:      $pattern');
  print('files:        ${files.isEmpty ? '(stdin)' : files}');
  print('ignore-case:  ${results.flag('ignore-case')}');
  print('line-numbers: ${results.flag('line-numbers')}');
  print('max-count:    $maxCount');
  print('color:        ${results.option('color')}');
  print('exclude:      ${results.multiOption('exclude')}');
  print('log-file:     ${results.option('log-file')}');
  return 0;
}

void main(List<String> args) {
  exitCode = run(args);
}

parser.usage is generated from the definitions, so the help text always matches what the program accepts:

$ dart bin/search.dart --help
Usage: search [options] <pattern> [<file>...]

-h, --help                    Show this help.
    --version                 Print the version.
-i, --[no-]ignore-case        Case-insensitive matching.
    --[no-]line-numbers       Prefix matches with line numbers.
                              (defaults to on)
-m, --max-count=<n>           Stop after <n> matches per file.
    --color                   When to use colors.

          [auto] (default)    Color only when writing to a terminal.
          [always]            Always use ANSI colors.
          [never]             Plain output.

    --exclude=<glob>          Skip matching files.
    --log-file                Write a debug log.

What the parameters do:

A normal run, then the errors:

$ dart bin/search.dart -i TODO lib bin --no-line-numbers -m 5 --exclude '*.g.dart' --exclude 'a,b' --logfile=dbg.txt --color=never
pattern:      TODO
files:        [lib, bin]
ignore-case:  true
line-numbers: false
max-count:    5
color:        never
exclude:      [*.g.dart, a,b]
log-file:     dbg.txt
$ dart bin/search.dart --color=sometimes x
search: "sometimes" is not an allowed value for option "--color".
Run "search --help" for usage.
$ dart bin/search.dart --colour x
search: Could not find an option named "--colour".
Run "search --help" for usage.
$ dart bin/search.dart --max-count
search: Missing argument for "--max-count".
Run "search --help" for usage.
$ dart bin/search.dart -m zero x
search: --max-count must be a positive integer, got "zero"
$ echo $?
64

parse throws ArgParserException, a subclass of FormatException, for unknown options, missing values and disallowed values. Catch it and print the message instead of letting the program crash with a stack trace.

Conventions for well-behaved command-line programs:

Splitting the program into buildParser(), run(args) that returns an exit code, and a one-line main makes it easy to test, as shown later.

Converting and validating values

args only deals with strings. Convert numbers, durations and so on yourself, and turn invalid values into the same kind of error as a parse failure. Here a server configuration is built from the command line, with the PORT environment variable as a fallback:

import 'dart:io';

import 'package:args/args.dart';

class Config {
  final String host;
  final int port;
  final Duration timeout;
  final bool verbose;
  Config(this.host, this.port, this.timeout, this.verbose);

  @override
  String toString() =>
      'Config(host: $host, port: $port, timeout: ${timeout.inSeconds}s, '
      'verbose: $verbose)';
}

final parser = ArgParser()
  ..addOption('host', defaultsTo: '127.0.0.1', help: 'Address to bind.')
  ..addOption('port', abbr: 'p', help: 'Port (default: \$PORT or 8000).')
  ..addOption('timeout', defaultsTo: '30', help: 'Request timeout in seconds.')
  ..addFlag('verbose', abbr: 'v', help: 'Log every request.');

/// Throws [FormatException] with a user-friendly message.
Config parseConfig(List<String> args, Map<String, String> env) {
  final r = parser.parse(args);

  int intOption(String name, String text, {int min = 0, int? max}) {
    final v = int.tryParse(text);
    if (v == null || v < min || (max != null && v > max)) {
      final range = max == null ? '>= $min' : '$min..$max';
      throw FormatException('--$name must be an integer $range, got "$text"');
    }
    return v;
  }

  // Precedence: command line, then environment, then default.
  final portText = r.option('port') ?? env['PORT'] ?? '8000';
  return Config(
    r.option('host')!,
    intOption('port', portText, max: 65535),
    Duration(seconds: intOption('timeout', r.option('timeout')!, min: 1)),
    r.flag('verbose'),
  );
}

void main(List<String> args) {
  try {
    print(parseConfig(args, Platform.environment));
  } on FormatException catch (e) {
    stderr.writeln('error: ${e.message}\n\n${parser.usage}');
    exitCode = 64;
  }
}

Output:

$ dart bin/config.dart
Config(host: 127.0.0.1, port: 8000, timeout: 30s, verbose: false)
$ PORT=9001 dart bin/config.dart -v
Config(host: 127.0.0.1, port: 9001, timeout: 30s, verbose: true)
$ PORT=9001 dart bin/config.dart --port 7000 --timeout 5
Config(host: 127.0.0.1, port: 7000, timeout: 5s, verbose: false)
$ dart bin/config.dart --timeout=0
error: --timeout must be an integer >= 1, got "0"
...
$ dart bin/config.dart -p 99999
error: --port must be an integer 0..65535, got "99999"

    --host            Address to bind.
                      (defaults to "127.0.0.1")
-p, --port            Port (default: $PORT or 8000).
    --timeout         Request timeout in seconds.
                      (defaults to "30")
-v, --[no-]verbose    Log every request.

The pattern is worth copying:

See Environment variables for more on reading configuration from the environment.

Mandatory options and other parser settings

args has a few more settings. Some of them behave differently than you might expect:

import 'package:args/args.dart';

void main() {
  // mandatory options
  final p1 = ArgParser()..addOption('host', mandatory: true);
  final r1 = p1.parse([]);
  print('parsed fine, wasParsed=${r1.wasParsed('host')}');
  try {
    r1.option('host');
  } on ArgumentError catch (e) {
    print('${e.runtimeType}: ${e.message}');
  }
  print(p1.parse(['--host', 'db1']).option('host'));

  // allowTrailingOptions
  final strict = ArgParser(allowTrailingOptions: false)..addFlag('verbose');
  final loose = ArgParser()..addFlag('verbose');
  final input = ['--verbose', 'run', 'x', '--verbose'];
  final s = strict.parse(input);
  final l = loose.parse(input);
  print('strict: verbose=${s.flag('verbose')} rest=${s.rest}');
  print('loose:  verbose=${l.flag('verbose')} rest=${l.rest}');

  // allowAnything
  final any = ArgParser.allowAnything().parse(['-x', '--foo=1', 'bar']);
  print('allowAnything rest: ${any.rest}');

  // callbacks
  final p2 = ArgParser()
    ..addOption('level', callback: (v) => print('level callback: $v'))
    ..addFlag('dry-run', callback: (v) => print('dry-run callback: $v'));
  p2.parse(['--level=3']);
}

Output:

parsed fine, wasParsed=false
ArgumentError: Option host is mandatory.
db1
strict: verbose=true rest=[run, x, --verbose]
loose:  verbose=true rest=[run, x]
allowAnything rest: [-x, --foo=1, bar]
level callback: 3
dry-run callback: false

Sub-commands

Tools like git, docker and dart itself have sub-commands, each with its own options. For a few simple ones, addCommand on ArgParser returns a nested parser:

import 'package:args/args.dart';

void main(List<String> args) {
  final parser = ArgParser()..addFlag('verbose', abbr: 'v');
  parser.addCommand('build').addOption('mode', defaultsTo: 'debug');
  parser.addCommand('clean');

  final r = parser.parse(args);
  final cmd = r.command;
  print('verbose: ${r.flag('verbose')}');
  switch (cmd?.name) {
    case 'build':
      print('build mode=${cmd!.option('mode')} targets=${cmd.rest}');
    case 'clean':
      print('clean');
    default:
      print('no command; commands: ${parser.commands.keys.toList()}');
  }
}

Output:

$ dart bin/subparse.dart -v build --mode release app web
verbose: true
build mode=release targets=[app, web]
$ dart bin/subparse.dart clean
verbose: false
clean
$ dart bin/subparse.dart
verbose: false
no command; commands: [build, clean]

For a real multi-command tool use CommandRunner from package:args/command_runner.dart. Each command is a class with its own parser, and the runner provides the help screens, a help command, error messages and "did you mean" suggestions. Here's a small note keeper:

import 'dart:io';

import 'package:args/command_runner.dart';

/// Base class with helpers for the global options.
abstract class NotesCommand extends Command<int> {
  File get notesFile => File(globalResults!.option('file')!);
  bool get verbose => globalResults!.flag('verbose');
}

class AddCommand extends NotesCommand {
  @override
  final name = 'add';
  @override
  final description = 'Add a note.';
  @override
  String get invocation => '${runner!.executableName} add [--pin] <text>';

  AddCommand() {
    argParser.addFlag('pin', abbr: 'p', help: 'Pin the note to the top.');
  }

  @override
  Future<int> run() async {
    final words = argResults!.rest;
    if (words.isEmpty) usageException('Missing note text.');
    final mark = argResults!.flag('pin') ? '*' : ' ';
    await notesFile.writeAsString('$mark ${words.join(' ')}\n',
        mode: FileMode.append);
    if (verbose) print('added to ${notesFile.path}');
    return 0;
  }
}

class ListCommand extends NotesCommand {
  @override
  final name = 'list';
  @override
  final description = 'List notes, pinned first.';
  @override
  final aliases = ['ls'];

  ListCommand() {
    argParser.addOption('limit',
        abbr: 'n', valueHelp: 'count', help: 'Show at most <count> notes.');
  }

  @override
  Future<int> run() async {
    final limitText = argResults!.option('limit');
    final limit = limitText == null ? null : int.tryParse(limitText);
    if (limitText != null && limit == null) {
      usageException('--limit must be a number, got "$limitText".');
    }
    if (!await notesFile.exists()) return 0;
    final lines = await notesFile.readAsLines();
    final sorted = [
      ...lines.where((l) => l.startsWith('*')),
      ...lines.where((l) => !l.startsWith('*')),
    ];
    for (final (i, line) in sorted.take(limit ?? sorted.length).indexed) {
      print('${i + 1}.$line');
    }
    return 0;
  }
}

Future<void> main(List<String> args) async {
  final runner = CommandRunner<int>('notes', 'A tiny note keeper.')
    ..argParser.addFlag('verbose', abbr: 'v', help: 'Print more output.')
    ..argParser.addOption('file',
        defaultsTo: 'notes.txt', help: 'Where notes are stored.')
    ..addCommand(AddCommand())
    ..addCommand(ListCommand());

  try {
    exitCode = await runner.run(args) ?? 0;
  } on UsageException catch (e) {
    stderr.writeln(e);
    exitCode = 64;
  }
}

Running it without arguments prints the generated overview:

$ dart bin/notes.dart
A tiny note keeper.

Usage: notes <command> [arguments]

Global options:
-h, --help            Print this usage information.
-v, --[no-]verbose    Print more output.
    --file            Where notes are stored.
                      (defaults to "notes.txt")

Available commands:
  add    Add a note.
  list   List notes, pinned first.

Run "notes help <command>" for more information about a command.

Using the commands:

$ dart bin/notes.dart add buy milk
$ dart bin/notes.dart -v add --pin call mom
added to notes.txt
$ dart bin/notes.dart add renew passport
$ dart bin/notes.dart ls
1.* call mom
2.  buy milk
3.  renew passport
$ dart bin/notes.dart list -n 2
1.* call mom
2.  buy milk
$ dart bin/notes.dart --file=work.txt add standup
$ dart bin/notes.dart help add
Add a note.

Usage: notes add [--pin] <text>
-h, --help        Print this usage information.
-p, --[no-]pin    Pin the note to the top.

Run "notes help" to see global options.

And the errors, all reported as a UsageException that includes the right usage text:

$ dart bin/notes.dart lst
Could not find a command named "lst".

Did you mean one of these?
  list


Usage: notes <command> [arguments]
...
$ dart bin/notes.dart list -n two
--limit must be a number, got "two".

Usage: notes list [arguments]
-h, --help             Print this usage information.
-n, --limit=<count>    Show at most <count> notes.

Run "notes help" to see global options.
$ dart bin/notes.dart add --urgent x
Could not find an option named "--urgent".

Usage: notes add [--pin] <text>
-h, --help        Print this usage information.
-p, --[no-]pin    Pin the note to the top.

Run "notes help" to see global options.

How it fits together:

Testing argument handling

Because buildParser and run from the search example are plain functions, tests can call them directly without starting a process:

import 'package:args/args.dart';
import 'package:test/test.dart';

import '../bin/search.dart';

void main() {
  final parser = buildParser();

  test('defaults', () {
    final r = parser.parse(['TODO']);
    expect(r.flag('ignore-case'), isFalse);
    expect(r.flag('line-numbers'), isTrue);
    expect(r.option('color'), 'auto');
    expect(r.rest, ['TODO']);
  });

  test('negated flag and repeated option', () {
    final r = parser.parse(
        ['--no-line-numbers', '--exclude', 'a', '--exclude', 'b', 'x']);
    expect(r.flag('line-numbers'), isFalse);
    expect(r.multiOption('exclude'), ['a', 'b']);
  });

  test('bad values are rejected', () {
    expect(() => parser.parse(['--color=pink']),
        throwsA(isA<ArgParserException>()));
  });

  test('exit codes', () {
    expect(run(['--version']), 0);
    expect(run([]), 64);
    expect(run(['-m', '0', 'x']), 64);
  });
}

Output:

$ dart test
...
00:00 +4: All tests passed!

For tests of the actual output, run the program as a child process with Process.run('dart', ['bin/search.dart', ...]) and check stdout, stderr and exitCode, or write output to an IOSink parameter instead of the global stdout.

Compiled executables and dart run

Arguments work the same way when the program is compiled with dart compile exe (see Compiling to executables):

$ dart compile exe bin/raw.dart -o raw.exe
$ ./raw.exe one "two three"
args: [one, two three] (2)
  [0] "one"
  [1] "two three"
script: raw.exe
VM flags: []

With dart run, everything after the script or executable name is passed to the program. Executables in a package's bin/ directory can be run by name with dart run <package>:<name>, or dart run :<name> for the current package. Notice that Platform.script is now a cached snapshot:

$ dart run :raw z
args: [z] (1)
  [0] "z"
script: raw.dart-3.13.4.snapshot
VM flags: [--packages=.dart_tool\package_config.json]

So don't derive the program name for help text from Platform.script; hard-code it, as the examples above do with CommandRunner('notes', ...).

Command-line arguments are read at run time. Values fixed at compile time, like a version number baked into the binary, use -D defines and String.fromEnvironment instead.

Summary

Task How
Get the arguments void main(List<String> args)
VM options (--enable-asserts, ...) Platform.executableArguments
Boolean switch addFlag('verbose', abbr: 'v'), read with results.flag('verbose')
Option with a value addOption('count', abbr: 'n', defaultsTo: '1'), results.option('count')
Repeatable option addMultiOption('tag'), results.multiOption('tag')
Positional arguments results.rest
Stop parsing options -- on the command line, or allowTrailingOptions: false
Restrict values allowed: [...], allowedHelp: {...}
Help text parser.usage, with help, valueHelp, hide
Turn off a default-on flag --no-<name> (flags are negatable by default)
Parse errors catch FormatException (ArgParserException), print to stderr, exit code 64
Numbers and other types int.tryParse and throw FormatException with a clear message
Environment fallback no defaultsTo, then results.option('port') ?? env['PORT'] ?? '8000'
Sub-commands CommandRunner + Command classes, usageException() for errors
Testing run(args) that returns an exit code, typed config object

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents