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.
What environment variables are
Section titled “What environment variables are”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:
APP_PORT=9000 ./serverOr for the rest of your terminal session:
export APP_PORT=9000./serverOn Windows PowerShell, that’s $env:APP_PORT = "9000". Like arguments, the values are always text. 9000 arrives as four characters, not a number.
Reading one variable
Section titled “Reading one variable”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});}HOME=/home/ada ./homeenv -i ./homeYou’ll see:
HOME: /home/adaHOME: nullenv -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.
Defaults with orelse
Section titled “Defaults with orelse”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 });}USER=ada ./helloenv -i ./helloYou’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.
Missing is not the same as empty
Section titled “Missing is not the same as empty”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", .{}); }}EDITOR=vim ./meEDITOR= ./meenv -u EDITOR ./meYou’ll see:
EDITOR is vimEDITOR is set, but emptyEDITOR 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.
Numbers and yes/no settings
Section titled “Numbers and yes/no settings”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;}./serverAPP_PORT=9000 APP_DEBUG=1 ./serverAPP_PORT=lots ./serverYou’ll see:
listening on port 8080, debug offlistening on port 9000, debug onerror: 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.
Only main can see the environment
Section titled “Only main can see the environment”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.
Passing the environment to your code
Section titled “Passing the environment to your code”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.logport=9000 debug=true log=app.logerror.BadPortstd.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.
Listing every variable
Section titled “Listing every variable”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 }); }}env -i COLOR=blue SIZE=10 ./listYou’ll see:
2 variablesCOLOR=blueSIZE=10Run it without env -i and you’ll get every variable your shell has, often more than a hundred.
Changing the environment
Section titled “Changing the environment”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 (
PathandPATHare the same variable), and Zig’s map follows that. On Linux and macOS,pathandPATHare 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.
Practice
Section titled “Practice”1. Greeting with a fallback
Section titled “1. Greeting with a fallback”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});}GREET_NAME=Ada ./greetGREET_NAME= ./greet./greetYou’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.
2. How many retries?
Section titled “2. How many retries?”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:
35error.BadRetriesorelse 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
HOMEorAPP_PORT. - Read one with
init.environ_map.get("NAME"). It returnsnullwhen the variable is missing. - Use
orelsefor defaults, and decide whether an empty value counts as missing. - Values are text: parse numbers with
std.fmt.parseIntand report bad values clearly. - Since 0.16, only
maingets 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Environment variables and process arguments become non-global (0.16 release notes): why only
maingets the environment, with examples forInitandInit.Minimal. - “Juicy main” (0.16 release notes): everything
std.process.Inithands tomain, includingenviron_map. - Optionals in the 0.17.1 reference:
?T,orelseandifwith optionals, which you use on everyget. - Standard library docs (0.17.1): look up
std.process.Environ.Mapforget,put,containsanditerator.