# Read command line arguments

**URL:** <https://ziggit.dev/t/read-command-line-arguments/220>\
**Category:** Help\
**Created:** [June 22, 2022, 9:47am UTC](https://ziggit.dev/t/read-command-line-arguments/220 "2022-06-22T09:47:25Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![ratfactor](https://ziggit.dev/user_avatar/ziggit.dev/ratfactor/32/48_2.png) [@ratfactor](https://ziggit.dev/u/ratfactor)\
**Post date:** [November 20, 2023, 6:19pm UTC](https://ziggit.dev/t/read-command-line-arguments/220/7 "2023-11-20T18:19:41Z")

</div>

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):

```zig
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:

```zig
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:

```bash
$ 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):

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

```

---

_[View the full topic](https://ziggit.dev/t/read-command-line-arguments/220)._
