Read command line arguments

Sorry to play necromancer on this thread, but this forum post continues to be the first thing that comes up when I search the Web for “zig args”, so I thought it would be nice to have a simple, complete, working example.

No allocations (won’t work on Windows or WASI)

Uses std.os.argv (prepopulated on program startup):

const std = @import("std");

pub fn main() !void {
    std.debug.print("There are {d} args:\n", .{std.os.argv.len});
    for(std.os.argv) |arg| {
        std.debug.print("  {s}\n", .{arg});
    }
}

Or with allocations

This uses std.process.argsAlloc() to parse the args into a handy array of strings:

const std = @import("std");

pub fn main() !void {
    // Get allocator
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    defer _ = gpa.deinit();

    // Parse args into string array (error union needs 'try')
    const args = try std.process.argsAlloc(allocator);
    defer std.process.argsFree(allocator, args);

    // Get and print them!
    std.debug.print("There are {d} args:\n", .{args.len});
    for(args) |arg| {
        std.debug.print("  {s}\n", .{arg});
    }
}

Building and running either version:

As separate steps:

$ zig build-exe arg-test.zig

$ ./arg-test foo bar baz
There are 4 args:
  ./arg-test
  foo
  bar
  baz

As a single step (what I usually do while developing):

$ zig run arg-test.zig -- foo bar baz
There are 4 args:
  /home/dave/.cache/zig/o/2679ea75d45ed3a8c27da28ac64a89b4/arg-test
  foo
  bar
  baz
12 Likes