Environment Variables

std.process.Init has a field environ_map that we can use to get environment variables:

const std = @import("std");
const print = std.debug.print;

pub fn main(init: std.process.Init) !void {
    const key = "COLOR";
    if (init.environ_map.get(key)) |value| {
        print("{s} is {s}\n", .{ key, value });
    } else {
        print("{s} not set\n", .{key});
    }
}
$ zig run environment.zig 
COLOR not set
$ COLOR=red zig run environment.zig 
COLOR is red

getPosix and getWindows let us access environment variables using just std.process.Init.Minimal, at the cost of portability:

const std = @import("std");
const print = std.debug.print;

pub fn main(minimal: std.process.Init.Minimal) !void {
    const key = "COLOR";
    if (minimal.environ.getPosix(key)) |val| {
        print("{s} is {s}\n", .{ key, val });
    } else {
        print("{s} not set\n", .{key});
    }
}
$ zig run environment-2.zig
COLOR not set
$ COLOR=blue zig run environment-2.zig
COLOR is blue

Next example: Exit Status.