Skip to content

Zig Environment Variables

Command-line arguments are what you type after a program’s name. Environment variables are the other kind of input a program gets when it starts: named settings like HOME, PATH or EDITOR that every program inherits from the shell that started it. They’re how you set things like a port number, a log level or an API key without typing them on every run. This page shows how to read them in Zig 0.17, what changed in 0.16, and how to keep code that depends on them easy to test.

An environment variable is a name and a text value, like EDITOR=vim. Your shell has a whole set of them, and every program it starts gets a copy. You can see yours with env (Linux and macOS) or set (Windows Command Prompt).

You can set one just for a single run by putting it in front of the command:

Terminal window
APP_PORT=9000 ./server

Or for the rest of your terminal session:

Terminal window
export APP_PORT=9000
./server

On Windows PowerShell, that’s $env:APP_PORT = "9000". Like arguments, the values are always text. 9000 arrives as four characters, not a number.

Zig hands the environment to main through init, the same std.process.Init parameter that gives you init.io and init.gpa (Zig Main & Init). init.environ_map is a map from names to values, and get looks one up:

const std = @import("std");
pub fn main(init: std.process.Init) void {
const home = init.environ_map.get("HOME");
std.debug.print("HOME: {?s}\n", .{home});
}
Terminal window
HOME=/home/ada ./home
env -i ./home

You’ll see:

HOME: /home/ada
HOME: null

env -i starts a program with an empty environment, which is a handy way to see what your program does when nothing is set.

get returns ?[]const u8: an optional string. It’s the string when the variable exists, and null when it doesn’t. That’s why the format uses {?s} (a string that might be null). You don’t free the result: the map owns it, and Zig cleans the map up when the program ends.

Most settings should have a sensible default, so the program works even when nobody set anything. orelse gives you one in a single line:

const std = @import("std");
pub fn main(init: std.process.Init) void {
const name = init.environ_map.get("USER") orelse "stranger";
const color = init.environ_map.get("APP_COLOR") orelse "blue";
std.debug.print("Hello, {s}! Your color is {s}.\n", .{ name, color });
}
Terminal window
USER=ada ./hello
env -i ./hello

You’ll see:

Hello, ada! Your color is blue.
Hello, stranger! Your color is blue.

x orelse y means “x if it’s there, otherwise y”, and the result is a plain []const u8, no longer optional. It’s the same orelse from Zig Optionals.

A variable can exist and still be empty. EDITOR= ./me sets EDITOR to an empty string, which is different from not setting it at all. get tells you which one you got:

const std = @import("std");
pub fn main(init: std.process.Init) void {
if (init.environ_map.get("EDITOR")) |editor| {
if (editor.len == 0) {
std.debug.print("EDITOR is set, but empty\n", .{});
} else {
std.debug.print("EDITOR is {s}\n", .{editor});
}
} else {
std.debug.print("EDITOR is not set\n", .{});
}
}
Terminal window
EDITOR=vim ./me
EDITOR= ./me
env -u EDITOR ./me

You’ll see:

EDITOR is vim
EDITOR is set, but empty
EDITOR is not set

(env -u NAME runs a program with that one variable removed.)

if (optional) |value| runs the first block with the value when there is one, and the else block for null. The language reference on if with optionals shows more forms of it.

Values are text, so a port number has to be parsed, just like a command-line argument. Decide what happens when it’s missing (use the default) and when it’s wrong (complain clearly, don’t quietly guess):

const std = @import("std");
pub fn main(init: std.process.Init) !u8 {
const port_text = init.environ_map.get("APP_PORT") orelse "8080";
const port = std.fmt.parseInt(u16, port_text, 10) catch {
std.debug.print("error: APP_PORT must be a number from 0 to 65535, got '{s}'\n", .{port_text});
return 1;
};
const debug = if (init.environ_map.get("APP_DEBUG")) |v| std.mem.eql(u8, v, "1") else false;
std.debug.print("listening on port {d}, debug {s}\n", .{ port, if (debug) "on" else "off" });
return 0;
}
Terminal window
./server
APP_PORT=9000 APP_DEBUG=1 ./server
APP_PORT=lots ./server

You’ll see:

listening on port 8080, debug off
listening on port 9000, debug on
error: APP_PORT must be a number from 0 to 65535, got 'lots'

std.fmt.parseInt is covered in Zig Command-Line Arguments. For yes/no settings there’s no standard rule, so pick one. Here only exactly 1 turns debug on; you could also accept true or yes with a few more std.mem.eql checks.

If you’ve used C, Python or Rust, you’re used to reading environment variables from anywhere: getenv("HOME"), os.environ["HOME"], std::env::var("HOME"). Older Zig had std.posix.getenv too. Since Zig 0.16 it’s gone:

const std = @import("std");
pub fn main() void {
const home = std.posix.getenv("HOME");
std.debug.print("{?s}\n", .{home});
}
main.zig:4:27: error: root source file struct 'posix' has no member named 'getenv'
const home = std.posix.getenv("HOME");
~~~~~~~~~^~~~~~~

This was on purpose. The environment is global state that any code could read or change at any time, which causes real bugs with threads, and in Zig it also couldn’t work in programs that don’t use the C library. So now the environment is only handed to main. The 0.16 release notes explain the full reasoning.

The rule that follows: if a function needs a setting, pass it in. Either pass the one value it needs (port: u16), or pass the whole map as a *const std.process.Environ.Map.

Here’s the payoff. A function that takes the map as a parameter can be called with a made-up environment, so you can check how it behaves without touching your real shell:

const std = @import("std");
const Config = struct {
port: u16,
debug: bool,
log_file: []const u8,
};
fn loadConfig(env: *const std.process.Environ.Map) !Config {
const port_text = env.get("APP_PORT") orelse "8080";
const port = std.fmt.parseInt(u16, port_text, 10) catch return error.BadPort;
const debug = if (env.get("APP_DEBUG")) |v| std.mem.eql(u8, v, "1") else false;
return .{
.port = port,
.debug = debug,
.log_file = env.get("APP_LOG") orelse "app.log",
};
}
fn show(env: *const std.process.Environ.Map) void {
if (loadConfig(env)) |c| {
std.debug.print("port={d} debug={} log={s}\n", .{ c.port, c.debug, c.log_file });
} else |err| {
std.debug.print("error.{t}\n", .{err});
}
}
pub fn main(init: std.process.Init) !void {
var env: std.process.Environ.Map = .init(init.gpa);
defer env.deinit();
show(&env); // nothing set: all defaults
try env.put("APP_PORT", "9000");
try env.put("APP_DEBUG", "1");
show(&env);
try env.put("APP_PORT", "lots");
show(&env);
}

Output:

port=8080 debug=false log=app.log
port=9000 debug=true log=app.log
error.BadPort

std.process.Environ.Map.init(gpa) makes an empty map, put adds or replaces a variable (it copies both strings, which is why it can fail and needs try), and deinit frees it all. In the real program, main just calls loadConfig(init.environ_map). Zig Testing shows how to turn checks like these into proper tests.

keys() and values() give you two slices in the same order, so you can loop over both at once:

const std = @import("std");
pub fn main(init: std.process.Init) void {
const env = init.environ_map;
std.debug.print("{d} variables\n", .{env.count()});
for (env.keys(), env.values()) |name, value| {
std.debug.print("{s}={s}\n", .{ name, value });
}
}
Terminal window
env -i COLOR=blue SIZE=10 ./list

You’ll see:

2 variables
COLOR=blue
SIZE=10

Run it without env -i and you’ll get every variable your shell has, often more than a hundred.

init.environ_map is a *Environ.Map, so you can change it with put and swapRemove. That only changes your program’s copy. It never changes the shell that started you, which is why a program can’t export something into your terminal.

Where it does matter is when you start other programs: you can give them a changed copy of the environment. Zig Processes shows how.

Two last details:

  • On Windows, names are case-insensitive (Path and PATH are the same variable), and Zig’s map follows that. On Linux and macOS, path and PATH are two different variables.
  • The map isn’t safe to change from several threads at once. Read your settings at startup, before you start any threads, and you’ll never have to think about it.

Write a program that prints Hello, <name>!, where the name comes from GREET_NAME. If it’s missing or empty, use friend.

Hint: get gives you an optional. Check null and len == 0.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) void {
var name: []const u8 = "friend";
if (init.environ_map.get("GREET_NAME")) |value| {
if (value.len > 0) name = value;
}
std.debug.print("Hello, {s}!\n", .{name});
}
Terminal window
GREET_NAME=Ada ./greet
GREET_NAME= ./greet
./greet

You’ll see:

Hello, Ada!
Hello, friend!
Hello, friend!

Starting with the default and only replacing it when there’s a non-empty value keeps the logic flat and easy to read.

Write retriesFrom(env: *const std.process.Environ.Map) !u8 that reads RETRIES, defaults to 3, and returns error.BadRetries if the value isn’t a number from 0 to 255. Test it from main with a made-up map.

Hint: std.fmt.parseInt(u8, text, 10) catch return error.BadRetries.

Show solution
const std = @import("std");
fn retriesFrom(env: *const std.process.Environ.Map) !u8 {
const text = env.get("RETRIES") orelse return 3;
return std.fmt.parseInt(u8, text, 10) catch return error.BadRetries;
}
pub fn main(init: std.process.Init) !void {
var env: std.process.Environ.Map = .init(init.gpa);
defer env.deinit();
std.debug.print("{d}\n", .{try retriesFrom(&env)});
try env.put("RETRIES", "5");
std.debug.print("{d}\n", .{try retriesFrom(&env)});
try env.put("RETRIES", "999");
if (retriesFrom(&env)) |n| {
std.debug.print("{d}\n", .{n});
} else |err| {
std.debug.print("error.{t}\n", .{err});
}
}

Output:

3
5
error.BadRetries

orelse return 3 returns the default straight away when the variable is missing. 999 doesn’t fit in a u8, so parseInt fails and the function turns that into its own, clearer error.

  • Environment variables are named text settings every program inherits from the shell, like HOME or APP_PORT.
  • Read one with init.environ_map.get("NAME"). It returns null when the variable is missing.
  • Use orelse for defaults, and decide whether an empty value counts as missing.
  • Values are text: parse numbers with std.fmt.parseInt and report bad values clearly.
  • Since 0.16, only main gets the environment. Pass settings, or a *const std.process.Environ.Map, to the code that needs them, which also makes that code easy to test with a made-up map.
  • Changing the map only changes your copy; it matters for the programs you start.

Next up: Zig Reading Input, reading what people type (or pipe in) while your program runs.

Quick check

1. What does init.environ_map.get("APP_PORT") return when APP_PORT isn't set?
2. You run EDITOR= ./app. What does get("EDITOR") give you?
3. A helper function deep in your program needs LOG_LEVEL. What's the Zig 0.17 way to give it access?
4. Your program calls init.environ_map.put("MODE", "fast"). What happens in the terminal that started it?