Zig CLI Tools
Command-line tools are where Zig feels most at home: a single small binary, starts instantly, no runtime to install, and cross-compiles to every major system with one flag. But a tool that works isn’t the same as a tool that’s nice to use. This page builds match, a small cousin of grep, and uses it to show the habits that make a CLI pleasant: clear help, sensible input and output, honest exit codes, and color that knows when to stay away. It ties together what you learned in Zig CLI Arguments, Zig Reading Input and Zig File I/O.
What makes a CLI pleasant
Section titled “What makes a CLI pleasant”Here’s the checklist we’ll follow. Most good Unix tools do all of it:
--helpexplains itself, and a mistake prints a short usage message instead of a stack trace.- Results go to stdout, messages go to stderr. Then
tool > out.txtsaves only the results, and errors still show up on screen. - Files as arguments, or stdin when there are none, so the tool works in a pipe:
cat log.txt | match error. - Exit codes mean something: 0 for success, non-zero for “no” or “broken”, so scripts can use
&&and||. - Fast output: buffer stdout and flush once at the end, instead of a system call per line.
- Color only on a terminal, never in a file or a pipe, and never when the user sets
NO_COLOR.
The tool: match
Section titled “The tool: match”match prints every line that contains a word. Here’s how it behaves, run on a small file notes.txt:
Zig is funRust is fun toozig fmt keeps code tidyThe end./match zig notes.txt./match -i -n zig notes.txtprintf 'one\ntwo\nthree\n' | ./match -n tYou’ll see:
zig fmt keeps code tidy1:Zig is fun3:zig fmt keeps code tidy2:two3:three-i ignores case, -n adds line numbers, and with no file, match reads stdin. We’ll build it in pieces, then show the whole program.
Parse arguments into an options struct
Section titled “Parse arguments into an options struct”Keep argument parsing in its own function that turns []const []const u8 into an Options struct. That keeps main short, and it makes the parser easy to test: it only takes a slice, so you can call it from a test without running the program at all. Mistakes come back as errors, and the diagnostics pattern passes back which argument was wrong. Here’s the parser with its tests:
const std = @import("std");
const Options = struct { ignore_case: bool = false, line_numbers: bool = false, pattern: []const u8 = "", files: []const []const u8 = &.{},};
const ParseError = error{ HelpRequested, UnknownOption, MissingPattern };
/// On `error.UnknownOption`, `bad_arg` is set to the option we didn't know.fn parseArgs(args: []const []const u8, bad_arg: *[]const u8) ParseError!Options { var opts: Options = .{}; var i: usize = 0; while (i < args.len) : (i += 1) { const arg = args[i]; if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) { return error.HelpRequested; } else if (std.mem.eql(u8, arg, "-i") or std.mem.eql(u8, arg, "--ignore-case")) { opts.ignore_case = true; } else if (std.mem.eql(u8, arg, "-n") or std.mem.eql(u8, arg, "--line-number")) { opts.line_numbers = true; } else if (arg.len > 1 and arg[0] == '-') { bad_arg.* = arg; return error.UnknownOption; } else { break; // the first plain word is the pattern } } if (i == args.len) return error.MissingPattern; opts.pattern = args[i]; opts.files = args[i + 1 ..]; return opts;}
test "flags and pattern" { var bad: []const u8 = ""; const opts = try parseArgs(&.{ "-i", "-n", "zig", "a.txt", "b.txt" }, &bad); try std.testing.expect(opts.ignore_case); try std.testing.expect(opts.line_numbers); try std.testing.expectEqualStrings("zig", opts.pattern); try std.testing.expectEqual(@as(usize, 2), opts.files.len);}
test "no files means stdin" { var bad: []const u8 = ""; const opts = try parseArgs(&.{"zig"}, &bad); try std.testing.expectEqual(@as(usize, 0), opts.files.len);}
test "mistakes" { var bad: []const u8 = ""; try std.testing.expectError(error.MissingPattern, parseArgs(&.{}, &bad)); try std.testing.expectError(error.HelpRequested, parseArgs(&.{"--help"}, &bad)); try std.testing.expectError(error.UnknownOption, parseArgs(&.{ "-x", "zig" }, &bad)); try std.testing.expectEqualStrings("-x", bad);}Output:
1/3 main.test.flags and pattern...OK2/3 main.test.no files means stdin...OK3/3 main.test.mistakes...OKAll 3 tests passed.Flags come first, then the pattern, then any number of files. opts.files is a slice of the original argument list, so it costs nothing. Note the arg.len > 1 check: a lone - is not an option. Many tools use it to mean “stdin” (that’s the second exercise below).
Hand-written parsing like this is fine for a handful of flags. For tools with many options, subcommands or --name=value forms, a community package such as zig-clap saves work; check which Zig version a package supports before you add it.
One search function for files and stdin
Section titled “One search function for files and stdin”The search shouldn’t care where lines come from. So it takes a *std.Io.Reader, and main hands it either a file’s reader or stdin’s reader:
/// Prints the lines of `in` that contain the pattern. Returns true if any did.fn search(in: *Io.Reader, term: Io.Terminal, opts: Options) !bool { const out = term.writer; var found = false; var line_no: usize = 0; while (try in.takeDelimiter('\n')) |line| { line_no += 1; const start = if (opts.ignore_case) std.ascii.findIgnoreCase(line, opts.pattern) else std.mem.find(u8, line, opts.pattern); const at = start orelse continue; found = true;
if (opts.line_numbers) { try term.setColor(.green); try out.print("{d}:", .{line_no}); try term.setColor(.reset); } const end = at + opts.pattern.len; try out.writeAll(line[0..at]); try term.setColor(.bright_red); try out.writeAll(line[at..end]); try term.setColor(.reset); try out.print("{s}\n", .{line[end..]}); } return found;}takeDelimiter('\n') returns one line at a time without the newline, and null at the end, exactly as in Zig Reading Input. The line is a slice into the reader’s buffer, so the buffer size is the longest line you can handle: match uses 64 KB, and a longer line gives error.StreamTooLong. term is explained in the color section below; for now, read term.writer as “stdout”.
stdout for results, stderr for messages
Section titled “stdout for results, stderr for messages”In main, matching lines go to a buffered stdout writer, flushed once at the end. Every message about the run (bad option, missing file) goes to stderr with std.debug.print. That split is what makes redirection work:
./match zig missing.txt notes.txt > found.txtYou’ll see this on screen:
match: missing.txt: FileNotFoundand found.txt contains only zig fmt keeps code tidy. If the error had gone to stdout, it would be hiding in the file, and the user would never see it.
Also notice that one missing file doesn’t stop the tool: it reports the problem, moves on to notes.txt, and remembers that something went wrong for the exit code.
Exit codes that scripts can trust
Section titled “Exit codes that scripts can trust”main returns !u8, and the number becomes the exit code. match uses the same convention as grep:
| Exit code | Meaning |
|---|---|
0 |
At least one line matched. |
1 |
It worked, but nothing matched. |
2 |
Something went wrong: bad option, missing pattern, unreadable file. |
So scripts can ask questions with it:
./match -i error app.log > /dev/null && echo "the log has errors"./match python notes.txt; echo "exit: $?"The second line prints exit: 1: no match, but not a failure. Separating “no” (1) from “broken” (2) lets a script tell “nothing found” apart from “couldn’t even look”. If main returns an error instead, Zig prints the error name (plus a stack trace in debug builds) and exits with code 1, which is fine for bugs but confusing for users, so handle the errors you expect and return a code yourself.
Color, but only on a terminal
Section titled “Color, but only on a terminal”Color helps people scan output, but escape codes are garbage in a file or in another program’s input. The standard library’s std.Io.Terminal decides for you:
const stdout_file = Io.File.stdout();var out_buf: [4096]u8 = undefined;var stdout = stdout_file.writer(io, &out_buf);const no_color = init.environ_map.get("NO_COLOR") != null;const term: Io.Terminal = .{ .writer = &stdout.interface, .mode = try .detect(io, stdout_file, no_color, false),};Mode.detect checks whether stdout is a terminal that understands color. If it isn’t (a file, a pipe), or if no_color is true, the mode is .no_color and every term.setColor(...) call does nothing. So search can call setColor freely and the output is always right. The NO_COLOR environment variable is a widely used convention for “I don’t want colors”; respecting it is polite. (The last argument is CLICOLOR_FORCE, for forcing color on; we pass false.)
When we ran ./match -n zig notes.txt in a real terminal, the raw bytes were:
^[[32m3:^[[0m^[[91mzig^[[0m fmt keeps code tidy^[[32m is “green” (the line number), ^[[91m is “bright red” (the match), and ^[[0m resets. The same command piped through cat printed plain 3:zig fmt keeps code tidy.
The whole program
Section titled “The whole program”Here’s all of match.zig together:
const std = @import("std");const Io = std.Io;
const usage = \\Usage: match [-i] [-n] PATTERN [FILE...] \\Print every line that contains PATTERN. \\With no FILE, read standard input. \\ \\ -i, --ignore-case ignore upper/lower case \\ -n, --line-number show line numbers \\ -h, --help show this help \\;
const Options = struct { ignore_case: bool = false, line_numbers: bool = false, pattern: []const u8 = "", files: []const []const u8 = &.{},};
const ParseError = error{ HelpRequested, UnknownOption, MissingPattern };
/// On `error.UnknownOption`, `bad_arg` is set to the option we didn't know.fn parseArgs(args: []const []const u8, bad_arg: *[]const u8) ParseError!Options { var opts: Options = .{}; var i: usize = 0; while (i < args.len) : (i += 1) { const arg = args[i]; if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) { return error.HelpRequested; } else if (std.mem.eql(u8, arg, "-i") or std.mem.eql(u8, arg, "--ignore-case")) { opts.ignore_case = true; } else if (std.mem.eql(u8, arg, "-n") or std.mem.eql(u8, arg, "--line-number")) { opts.line_numbers = true; } else if (arg.len > 1 and arg[0] == '-') { bad_arg.* = arg; return error.UnknownOption; } else { break; // the first plain word is the pattern } } if (i == args.len) return error.MissingPattern; opts.pattern = args[i]; opts.files = args[i + 1 ..]; return opts;}
/// Prints the lines of `in` that contain the pattern. Returns true if any did.fn search(in: *Io.Reader, term: Io.Terminal, opts: Options) !bool { const out = term.writer; var found = false; var line_no: usize = 0; while (try in.takeDelimiter('\n')) |line| { line_no += 1; const start = if (opts.ignore_case) std.ascii.findIgnoreCase(line, opts.pattern) else std.mem.find(u8, line, opts.pattern); const at = start orelse continue; found = true;
if (opts.line_numbers) { try term.setColor(.green); try out.print("{d}:", .{line_no}); try term.setColor(.reset); } const end = at + opts.pattern.len; try out.writeAll(line[0..at]); try term.setColor(.bright_red); try out.writeAll(line[at..end]); try term.setColor(.reset); try out.print("{s}\n", .{line[end..]}); } return found;}
pub fn main(init: std.process.Init) !u8 { const io = init.io; const args = try init.minimal.args.toSlice(init.arena.allocator());
var bad_arg: []const u8 = ""; const opts = parseArgs(args[1..], &bad_arg) catch |err| switch (err) { error.HelpRequested => { try Io.File.stdout().writeStreamingAll(io, usage); return 0; }, error.UnknownOption => { std.debug.print("match: unknown option '{s}'\n{s}", .{ bad_arg, usage }); return 2; }, error.MissingPattern => { std.debug.print("match: missing PATTERN\n{s}", .{usage}); return 2; }, };
const stdout_file = Io.File.stdout(); var out_buf: [4096]u8 = undefined; var stdout = stdout_file.writer(io, &out_buf); const no_color = init.environ_map.get("NO_COLOR") != null; const term: Io.Terminal = .{ .writer = &stdout.interface, .mode = try .detect(io, stdout_file, no_color, false), };
var found = false; var had_error = false; var in_buf: [64 * 1024]u8 = undefined;
if (opts.files.len == 0) { var stdin = Io.File.stdin().reader(io, &in_buf); found = try search(&stdin.interface, term, opts); } else for (opts.files) |path| { const file = Io.Dir.cwd().openFile(io, path, .{}) catch |err| { std.debug.print("match: {s}: {t}\n", .{ path, err }); had_error = true; continue; }; defer file.close(io); var reader = file.reader(io, &in_buf); if (try search(&reader.interface, term, opts)) found = true; }
try stdout.interface.flush(); if (had_error) return 2; return if (found) 0 else 1;}Build it with zig build-exe match.zig -O safe and try the mistakes too:
./match -x zigYou’ll see (on stderr, with exit code 2):
match: unknown option '-x'Usage: match [-i] [-n] PATTERN [FILE...]Print every line that contains PATTERN.With no FILE, read standard input.
-i, --ignore-case ignore upper/lower case -n, --line-number show line numbers -h, --help show this help./match --help prints the same help on stdout with exit code 0, because there the help is the result the user asked for. That’s why it uses writeStreamingAll on stdout instead of std.debug.print.
Practice
Section titled “Practice”1. Add -c / --count
Section titled “1. Add -c / --count”Add a flag that prints only the number of matching lines (across all files) instead of the lines. Exit codes stay the same.
Hint: add count: bool = false to Options, make search return a usize count instead of a bool, skip printing when opts.count is set, and print the total in main before the flush.
Show solution
The changed parts:
// In Options:count: bool = false,
// In parseArgs, next to the other flags:} else if (std.mem.eql(u8, arg, "-c") or std.mem.eql(u8, arg, "--count")) { opts.count = true;
// search now returns how many lines matched:fn search(in: *Io.Reader, term: Io.Terminal, opts: Options) !usize { const out = term.writer; var found: usize = 0; // ... same loop, but after a match: // found += 1; // if (opts.count) continue; // count only, print nothing}
// In main:var found: usize = 0;// ...found += try search(&reader.interface, term, opts);// ...if (opts.count) try stdout.interface.print("{d}\n", .{found});try stdout.interface.flush();if (had_error) return 2;return if (found > 0) 0 else 1;With notes.txt from above:
./match -c -i zig notes.txt # exit code 0./match --count fun notes.txt notes.txt./match -c python notes.txt # exit code 1You’ll see:
240Also add the flag to the usage text, so --help stays honest. Returning a number instead of a bool is a small change that made a new feature almost free.
2. Let - mean stdin
Section titled “2. Let - mean stdin”Many tools treat a file name of - as “read stdin here”. Make printf 'zig from a pipe\n' | ./match zig notes.txt - search both the file and the pipe.
Hint: in the loop over opts.files, check for "-" before opening a file, and use stdin’s reader for it. parseArgs already lets a lone - through, thanks to the arg.len > 1 check.
Show solution
At the top of the for (opts.files) |path| loop:
if (std.mem.eql(u8, path, "-")) { var stdin = Io.File.stdin().reader(io, &in_buf); if (try search(&stdin.interface, term, opts)) found = true; continue;}printf 'zig from a pipe\nnothing here\n' | ./match zig notes.txt -You’ll see:
zig fmt keeps code tidyzig from a pipeThe file’s match comes first, then the pipe’s, in the order the names were given. Because search takes any *Io.Reader, supporting a new input source was four lines.
- A pleasant CLI has
--help, clear usage errors, results on stdout and messages on stderr. - Parse arguments into an options struct in a separate function you can unit test.
- Write the core logic against
*std.Io.Reader, so files and stdin share one code path. - Buffer stdout and flush once at the end.
- Return meaningful exit codes from
main(!u8), like grep’s 0, 1 and 2. - Use
std.Io.TerminalwithMode.detectso colors appear only on a terminal, and respectNO_COLOR.
Next up: Zig in the Real World, the projects that use Zig today and what they use it for.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Choosing an Allocator: why an arena (like
init.arena) suits command-line tools. - std.Io.Terminal source (0.17.1):
Mode.detect,setColorand the color names. - Command Line Interface Guidelines: a widely read, language-neutral guide to making command-line tools pleasant.
- NO_COLOR: the convention for turning colors off.
- zig-clap: a community argument-parsing package for bigger tools.