Skip to content

Lesson 7 of 9 · 24m

Designing Real Command-Line Utilities

Design argument parsing, stdin/stdout behavior, exit codes, filesystem effects, and diagnostics as the utility's public contract.

A command-line utility is an API with worse documentation and more demanding users. Shells compose it, scripts depend on its exit codes, cron captures its output, and people pipe untrusted data through it. If you design only the happy path, the utility will become unreliable exactly where systems tools matter: automation.

Start with the contract

Before opening the editor, write down the interface:

spray [options] <path...>

--format json|text       output format (default: text)
--max-size bytes         refuse files larger than this
--follow-symlinks        traverse symlink targets
--jobs n                 worker count
-q, --quiet              suppress progress output
--help                   print usage
--version                print version

Then decide stream semantics. Machine-readable output belongs on stdout. Progress, warnings, and diagnostics belong on stderr. Never mix progress noise into data that a pipeline is expected to parse.

Parse arguments deliberately

Zig does not force one CLI parser on you. For small utilities, explicit parsing is often clearer than framework magic:

var args = try std.process.argsWithAllocator(allocator);
defer args.deinit();
_ = args.next(); // executable name

var max_size: usize = 16 * 1024 * 1024;
var json = false;
while (args.next()) |arg| {
    if (std.mem.eql(u8, arg, "--format")) {
        const value = args.next() orelse return error.MissingFormatValue;
        json = std.mem.eql(u8, value, "json");
    } else if (std.mem.eql(u8, arg, "--help")) {
        return printHelp();
    }
}

Manual parsing scales poorly to dozens of options, but it forces you to understand ambiguity: repeated flags, -- terminator, missing values, short-option clustering, and unknown arguments.

Exit codes are part of compatibility

Do not return success because the process reached main completion. Return success because the requested operation succeeded:

0   all requested work succeeded
1   operational failure or invalid input
2   command-line usage error

Some tools need richer codes, but do not invent them casually. Scripts encode these numbers. Document whether partial success is success, failure, or a distinct result.

File traversal is adversarial input

Walking directories means symlinks, races, permission errors, hard links, deep recursion, bizarre filenames, and files that change while being read. Use explicit options and bounded behavior:

var dir = try std.fs.cwd().openDir(path, .{ .iterate = true });
defer dir.close();

var it = dir.iterate();
while (try it.next()) |entry| {
    std.debug.print("{s}\t{s}\n", .{ @tagName(entry.kind), entry.name });
}

A production walker needs cycle detection, symlink policy, depth limits, and an error policy. Continue on permission denied? Abort on first failure? Report and count? Different tools choose differently, but ambiguity is not an option.

Small example: bytes in, bytes out

The best utilities compose:

spray --format json ./src | jq '.files[] | select(.size > 1048576)'
find . -type f -print0 | xargs -0 spray

If filenames may contain newline or control characters, line-delimited text is not a safe interchange format. JSON Lines or NUL-separated output may be better. Choose based on consumers, not aesthetics.

Field notes

  • Treat -- as the end of options if paths can begin with hyphens.
  • Do not silently accept unknown options; typos in automation become missing safety controls.
  • --quiet should reduce progress chatter, not hide errors that affect the exit status.
  • stdout buffering changes ordering when output is piped. If humans need timely progress, write progress to stderr and flush deliberately.
  • Avoid destructive flags without explicit confirmation or obvious naming. overwrite and delete-source should never be defaults.
  • Shell quoting is not your parsing layer, but filenames containing whitespace and newlines are still real inputs.

Was this lesson helpful?

Sign in to rate