DEV Community

Cover image for You have been zigged (series) : Accessing environment variables
Black Tornado
Black Tornado

Posted on

You have been zigged (series) : Accessing environment variables

Accessing environment variables

Environment variables are key-value pairs given to a process by the operating system right before it starts. They are mainly used to configure the process on runtime. In C/C++, the environment variables are passed to the main function as arguments. In zig, the environment variables are can be accessed from the init object which is passed to the main function as argument. Let's see how that works.

Program - Printing all inherited environment variables using zig.

To print out all the environment variables, we will utilize the environment variable iterator.

// environment_vars1.zig
const std = @import("std");

pub fn main(init: std.process.Init) !void {
    var env_vars_iterator = init.environ_map.iterator();

    // setup stdout writer
    var buffer: [1024]u8 = undefined;
    var file_writer = std.Io.File.Writer.init(.stdout(), init.io, &buffer);
    var stdout_writer = &file_writer.interface;

    while (env_vars_iterator.next()) |env_var| {
        try stdout_writer.print("{s} \n {s}\n\n", .{ env_var.key_ptr.*, env_var.value_ptr.* });
    }
    try stdout_writer.flush();
}

Enter fullscreen mode Exit fullscreen mode

You can run the program using zig run environment_vars1.zig. This will print out all the environment variables to console. To build executable zig build-exe -O ReleaseSafe environment_vars1.zig

Program - Printing the value of a user selected environment variable using zig.

In this program we are going to setup a Reader which can read from stdin. We will first print out the names of all the environment variables using the iterator we used in the above program and then using aforementioned reader instance, we will let the user type in the name of an environment variable. If they entered a existing environment variable name, we will retrieve the value of that environment variable using the get function and print the value of that environment variable. If the user entered a non-existing environment variable name, we will error out using InvalidEnvVariableEntered.

// environment_vars2.zig
const std = @import("std");

pub fn main(init: std.process.Init) !void {
    // setting up stdout writer
    var stdout_buffer: [1024]u8 = undefined;
    var file_writer: std.Io.File.Writer = .init(.stdout(), init.io, &stdout_buffer);
    var stdout_writer = &file_writer.interface;

    // setting up stdin reader
    var stdin_buffer: [1024]u8 = undefined;
    var file_reader: std.Io.File.Reader = .init(.stdin(), init.io, &stdin_buffer);
    var stdin_reader = &file_reader.interface;

    try stdout_writer.print("Printing all environment variable names...\n", .{});
    var env_vars_iterator = init.environ_map.iterator();
    while (env_vars_iterator.next()) |env_var| {
        try stdout_writer.print(" {s}\n", .{env_var.key_ptr.*});
    }

    // fetch the name of env variable whose value we need to display
    try stdout_writer.print("Enter the name of an environment variable to see its value :", .{});
    try stdout_writer.flush();
    const userinput = try stdin_reader.takeDelimiterExclusive('\n');
    const userinput_trimmed = std.mem.trimEnd(u8, userinput[0..userinput.len], "\r");
    const env_var_value = init.environ_map.get(userinput_trimmed);
    if (env_var_value == null) {
        try stdout_writer.flush();
        return error.InvalidEnvVariableEntered;
    }
    try stdout_writer.print("{s} => {s}\n", .{ userinput_trimmed, env_var_value.? });
    try stdout_writer.flush();
}
Enter fullscreen mode Exit fullscreen mode

You can run the program using zig run environment_vars2.zig. To build executable zig build-exe -O ReleaseSafe environment_vars2.zig.

Thanks for reading. To be continued.

Top comments (0)