Skip to content

Zig Command-Line Arguments

Most useful programs take some input when you start them: git commit -m "fix", zig build run, ls -la. Those extra words are command-line arguments, and they’re the easiest way to tell your program what to do without asking questions while it runs. This page shows how to read them in Zig 0.17, how to turn "42" into the number 42, what to do when someone types the wrong thing, and how to tell the shell whether your program worked.

When you type a command, the shell splits it into words at the spaces and hands your program a list of strings. Quotes keep words together:

Terminal window
./greet Ada "Grace Hopper" 42

Your program gets four strings:

Index Value
0 ./greet
1 Ada
2 Grace Hopper
3 42

Two things surprise people at first:

  • Index 0 is the program itself, the way it was started. Your real arguments start at index 1. C, Python’s sys.argv and Rust’s std::env::args all work the same way.
  • Everything is text. 42 arrives as the two characters '4' and '2', not as a number. You convert it yourself (more on that below).

Arguments come in through main. Since Zig 0.16, main can take an init: std.process.Init parameter, and the arguments live in init.minimal.args. The easiest way to use them is to turn them into a slice:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const args = try init.minimal.args.toSlice(init.arena.allocator());
std.debug.print("You passed {d} argument(s)\n", .{args.len});
for (args, 0..) |arg, i| {
std.debug.print(" args[{d}] = {s}\n", .{ i, arg });
}
}

Build it and run it with a few arguments:

Terminal window
zig build-exe args.zig
./args hello "two words" 42

You’ll see:

You passed 4 argument(s)
args[0] = ./args
args[1] = hello
args[2] = two words
args[3] = 42

What’s going on:

  • init.minimal.args.toSlice(...) gives you a slice of strings, []const [:0]const u8. Each string is zero-terminated (that’s the :0, see Zig Sentinels), but you can use it like any other []const u8.
  • It needs an allocator to build the slice, and the standard library asks for an arena here, because the result can point into several allocations. init.arena is an arena that lives as long as the program and is cleaned up for you when it ends, so you never free the arguments yourself. Zig Arena Allocator explains arenas.
  • It can fail (with error.OutOfMemory), so it needs try, and main returns !void.

You don’t have to build an executable every time. Put your arguments after --, and Zig passes everything after it to your program instead of reading it itself:

Terminal window
zig run args.zig -- hello world
zig build run -- hello world

The first line works on a single file. The second works in a project made with zig init, whose build.zig already has run_cmd.addPassthruArgs() for exactly this. With zig run, args[0] is a long path inside Zig’s cache folder, and with zig build run it’s something like ./zig-out/bin/myapp. That’s one more reason never to rely on the exact text of args[0].

Here’s the mistake everyone makes once. This program reads a name from args[1]:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const args = try init.minimal.args.toSlice(init.arena.allocator());
const name = args[1];
std.debug.print("Hello, {s}!\n", .{name});
}

With an argument it works. Without one, args has only one item, and you’ll see something like:

thread 8469 panic: index out of bounds: index 1, len 1
oob.zig:5:22: 0x11e429c in main (oob.zig)
const name = args[1];
^

A crash with a stack trace is a rude way to say “you forgot the name”. Check args.len first and print a usage message that tells people how to call the program:

const std = @import("std");
pub fn main(init: std.process.Init) !u8 {
const args = try init.minimal.args.toSlice(init.arena.allocator());
if (args.len != 2) {
std.debug.print("usage: greet <name>\n", .{});
return 2;
}
std.debug.print("Hello, {s}!\n", .{args[1]});
return 0;
}
Terminal window
./greet
./greet Ada

You’ll see:

usage: greet <name>
Hello, Ada!

The usage line goes to stderr (that’s where std.debug.print writes, see Zig Output), because it’s a message about the program, not its result. And main now returns !u8 instead of !void: the number it returns becomes the program’s exit code. The next sections explain why that number matters.

Arguments are text, so "42" has to be parsed. std.fmt.parseInt(T, text, base) does it: T is the integer type you want, and base is 10 for normal numbers. It returns an error union, because plenty of text isn’t a number:

const std = @import("std");
pub fn main() void {
const inputs = [_][]const u8{ "42", "-7", "300", "12abc", "", " 5", "0x1F" };
for (inputs) |text| {
if (std.fmt.parseInt(u8, text, 10)) |n| {
std.debug.print("\"{s}\" -> {d}\n", .{ text, n });
} else |err| {
std.debug.print("\"{s}\" -> error.{t}\n", .{ text, err });
}
}
}

Output:

"42" -> 42
"-7" -> error.Overflow
"300" -> error.Overflow
"12abc" -> error.InvalidCharacter
"" -> error.InvalidCharacter
" 5" -> error.InvalidCharacter
"0x1F" -> error.InvalidCharacter

There are only two errors to handle:

  • error.InvalidCharacter: the text isn’t a number at all. An empty string and a leading space count too, so trim input you didn’t type yourself.
  • error.Overflow: it is a number, but it doesn’t fit in the type. 300 is too big for a u8, and -7 doesn’t fit in any unsigned type, so it’s also Overflow, not “invalid”.

Pass 0 as the base and parseInt reads prefixes too: "0x1F" becomes 31, "0b101" becomes 5. For decimals there’s std.fmt.parseFloat(f64, text).

You could just write try std.fmt.parseInt(...). If someone types abc, the error goes up out of main, and in a debug build you’ll see something like this (trimmed):

error: InvalidCharacter
.../std/fmt.zig:583:24: 0x10f5e5a in charToDigit (std.zig)
if (value >= base) return error.InvalidCharacter;
^
repeat.zig:11:19: 0x11e43c1 in main (repeat.zig)
const times = try std.fmt.parseInt(u32, args[1], 10);
^

That trace is great while you are debugging, and confusing for anyone else. Catch the error and say what went wrong in plain words instead:

const std = @import("std");
pub fn main(init: std.process.Init) !u8 {
const args = try init.minimal.args.toSlice(init.arena.allocator());
if (args.len != 3) {
std.debug.print("usage: repeat <times> <word>\n", .{});
return 2;
}
const times = std.fmt.parseInt(u32, args[1], 10) catch {
std.debug.print("error: '{s}' is not a whole number\n", .{args[1]});
return 2;
};
for (0..times) |_| std.debug.print("{s} ", .{args[2]});
std.debug.print("\n", .{});
return 0;
}
Terminal window
./repeat 3 hi
./repeat abc hi

You’ll see:

hi hi hi
error: 'abc' is not a whole number

catch { ... } runs its block when parseInt fails, and the block returns from main before times is ever used. Zig Try & Catch covers catch in depth.

Every program ends with a small number, its exit code. 0 means “it worked”, anything else means “something went wrong”. You don’t see it, but shells and scripts do. In a terminal on Linux or macOS, echo $? prints the last one:

Terminal window
./repeat 3 hi; echo $?
./repeat abc hi; echo $?

You’ll see:

hi hi hi
0
error: 'abc' is not a whole number
2

Scripts use this all the time: ./build && ./deploy only deploys if the build exited with 0, and CI marks a job as failed when a step exits with anything else.

Here’s how a Zig program picks its exit code:

How main ends Exit code
main returns void (or !void without an error) 0
main returns an error 1, after printing error: <Name>
main returns a u8 (or !u8) the number you return
std.process.exit(n) anywhere n
a panic (like the index out of bounds above) the program aborts, 134 on Linux

There’s no official meaning for codes other than 0, but a common habit (from Unix tools) is 1 for “it failed” and 2 for “you called me wrong”, which is what the examples here use.

std.process.exit(n) stops the whole program on the spot, from any function. That’s handy deep inside a program, but “on the spot” means no defer runs, and that includes flushing a buffered writer:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
var buffer: [256]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(init.io, &buffer);
const out = &stdout_writer.interface;
defer out.flush() catch {};
try out.print("working on it...\n", .{});
std.process.exit(3);
}

This prints nothing and exits with 3. The text was waiting in the buffer, and the defer that would have flushed it never ran. Change the last line to return from a main that returns !u8 (return 3;), and the defer runs, the text appears, and the exit code is still 3.

Real tools take options like -v or -n 3. Zig’s standard library doesn’t have an argument parser (the release notes mention one is being discussed), so small programs walk through the arguments by hand. It’s less work than it sounds.

The trick that makes this easy to test: put the parsing in a function that takes the slice, instead of reading arguments inside it. Then you can feed it a made-up list, like this program does:

const std = @import("std");
const Options = struct {
count: u32 = 1,
verbose: bool = false,
name: []const u8 = "world",
};
const ParseError = error{ MissingValue, BadNumber, UnknownOption };
fn parseArgs(args: []const [:0]const u8) ParseError!Options {
var opts: Options = .{};
var i: usize = 1; // args[0] is the program
while (i < args.len) : (i += 1) {
const arg = args[i];
if (std.mem.eql(u8, arg, "-v") or std.mem.eql(u8, arg, "--verbose")) {
opts.verbose = true;
} else if (std.mem.eql(u8, arg, "-n")) {
i += 1;
if (i == args.len) return error.MissingValue;
opts.count = std.fmt.parseInt(u32, args[i], 10) catch return error.BadNumber;
} else if (std.mem.startsWith(u8, arg, "-")) {
return error.UnknownOption;
} else {
opts.name = arg;
}
}
return opts;
}
pub fn main() void {
const tries = [_][]const [:0]const u8{
&.{"greet"},
&.{ "greet", "-n", "3", "Zig" },
&.{ "greet", "--verbose", "Ada" },
&.{ "greet", "-n" },
&.{ "greet", "-n", "three" },
&.{ "greet", "--color" },
};
for (tries) |args| {
if (parseArgs(args)) |o| {
std.debug.print("count={d} verbose={} name={s}\n", .{ o.count, o.verbose, o.name });
} else |err| {
std.debug.print("error.{t}\n", .{err});
}
}
}

Output:

count=1 verbose=false name=world
count=3 verbose=false name=Zig
count=1 verbose=true name=Ada
error.MissingValue
error.BadNumber
error.UnknownOption

A few things to notice:

  • Strings are compared with std.mem.eql(u8, a, b). == doesn’t work on string contents in Zig (Zig Strings explains why).
  • Options has a default for every field, so .{} is a valid “nothing given” starting point.
  • -n reads the next argument as its value, so the loop moves i forward by one more and checks that there was a next one.
  • Anything else starting with - is an unknown option, and everything left over is the name.

In the real program, main calls parseArgs with the slice from toSlice, catches the error, prints a usage message and returns 2. The parser itself never touches init, which is why you could test it with fake lists here. You’ll do exactly that with zig test in Zig Testing.

If you’d rather not build a slice, you can walk the arguments with an iterator. It works like any Zig iterator: next() returns the next argument, or null at the end (while with optionals in the reference).

const std = @import("std");
pub fn main(init: std.process.Init) !void {
var it = try init.minimal.args.iterateAllocator(init.gpa);
defer it.deinit();
_ = it.skip(); // skip args[0], the program name
while (it.next()) |arg| {
std.debug.print("got: {s}\n", .{arg});
}
}
Terminal window
./each one two

You’ll see:

got: one
got: two

skip() moves past one argument without giving it to you. There’s also a plain iterate() that needs no allocator, but it only works on some systems (on Windows the command line arrives as one long string that has to be split up, which needs memory). iterateAllocator works everywhere, so use it, and don’t forget the deinit.

For most programs, toSlice with the arena is simpler: you can look at args.len, index into it, and pass it to functions.

Write sum, a program that adds up all of its arguments as whole numbers (i64) and prints the total. ./sum 10 20 -5 prints 25. If an argument isn’t a number, print which one and exit with code 1.

Hint: loop over args[1..] (everything except the program name) and use std.fmt.parseInt(i64, arg, 10).

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !u8 {
const args = try init.minimal.args.toSlice(init.arena.allocator());
var total: i64 = 0;
for (args[1..]) |arg| {
const n = std.fmt.parseInt(i64, arg, 10) catch {
std.debug.print("error: '{s}' is not a whole number\n", .{arg});
return 1;
};
total += n;
}
std.debug.print("{d}\n", .{total});
return 0;
}
Terminal window
./sum 10 20 -5
./sum 1 two 3
./sum

You’ll see:

25
error: 'two' is not a whole number
0

args[1..] is a slice starting after the program name, so it’s empty when there are no arguments, and the total stays 0. Since i64 is signed, -5 parses fine.

This program crashes with “index out of bounds” when you run it without arguments. Make it print usage: hello <name> and exit with code 2 instead.

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const args = try init.minimal.args.toSlice(init.arena.allocator());
std.debug.print("Hello, {s}!\n", .{args[1]});
}

Hint: change the return type so main can return a number, and check args.len first.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !u8 {
const args = try init.minimal.args.toSlice(init.arena.allocator());
if (args.len < 2) {
std.debug.print("usage: hello <name>\n", .{});
return 2;
}
std.debug.print("Hello, {s}!\n", .{args[1]});
return 0;
}
Terminal window
./hello; echo $?

You’ll see:

usage: hello <name>
2

args.len < 2 means there’s nothing besides the program name. Returning 2 from a main that returns !u8 sets the exit code, and any defers still run.

Extend parseArgs from the page with a --shout flag that sets a shout: bool field. Test it with fake arguments, the same way the page does.

Hint: add shout: bool = false to Options and one more else if branch before the startsWith check.

Show solution
const std = @import("std");
const Options = struct {
name: []const u8 = "world",
shout: bool = false,
};
fn parseArgs(args: []const [:0]const u8) error{UnknownOption}!Options {
var opts: Options = .{};
for (args[1..]) |arg| {
if (std.mem.eql(u8, arg, "--shout")) {
opts.shout = true;
} else if (std.mem.startsWith(u8, arg, "-")) {
return error.UnknownOption;
} else {
opts.name = arg;
}
}
return opts;
}
pub fn main() void {
const a = parseArgs(&.{ "hello", "--shout", "Ada" }) catch unreachable;
const b = parseArgs(&.{ "hello", "Zig" }) catch unreachable;
std.debug.print("name={s} shout={}\n", .{ a.name, a.shout });
std.debug.print("name={s} shout={}\n", .{ b.name, b.shout });
}

Output:

name=Ada shout=true
name=Zig shout=false

With no option that takes a value, a plain for loop over args[1..] is enough. catch unreachable is fine here only because these test lists are known to be valid; real input should get a usage message instead.

  • Arguments arrive as text, and args[0] is the program itself. Your arguments start at index 1.
  • Read them with init.minimal.args.toSlice(init.arena.allocator()): a slice you can index and pass around, freed for you when the program ends.
  • Check args.len before indexing, and print a usage message to stderr when the input is wrong.
  • std.fmt.parseInt(T, text, 10) turns text into a number and fails with InvalidCharacter or Overflow. Catch it and explain the problem in plain words.
  • The exit code tells scripts how it went: return a u8 from main, or call std.process.exit(n), which skips defers.
  • Put option parsing in a function that takes the slice, so you can test it without a terminal.

Next up: Zig Environment Variables, the other kind of input a program gets when it starts.

Quick check

1. You run ./tool build fast. What is args[1]?
2. What does std.fmt.parseInt(u8, "300", 10) return?
3. Why might output written to a buffered stdout writer disappear when you call std.process.exit(1)?
4. A program's main returns error.ConfigMissing. What exit code does the shell see?