An environment variable refers to a mechanism for provisioning dynamic configuration information to Unix programs at runtime. Environment variables are very useful as they help define dynamic configuration and behaviors for applications based on the environment.

In Linux systems, examples of environment variables include the location of executable programs within the filesystem, the user shell, pwd, home directory for a specific user, motd, and many more.

Go, a modern and vast programming language provides the os package to interact with environment variables.

We will cover the fundamentals of working with environment variables in the Go language throughout this tutorial.

Getenv

The first method we are going to cover is the Getenv method. This method allows you to retrieve the values of an environment variable. The function takes the environment variable’s name as the parameter and returns its associated value.

If the environment variable specified does not exist on the system, the function returns an empty value. This may be a little confusing if the environment variable exists but is unset.

The function syntax is as shown:

Consider the example below:

package main


import (


    “fmt”


    “os”

)


func main() {


    fmt.Println(“Home: “, os.Getenv(“HOME”))

}

The example will retrieve the value of the home directory for the user. An example output is as shown:

$ go run getenv.go


Home:  C:Userscsalem // windows


Home: /home/debian // Debian

LookupEnv

As mentioned, the GetEnv function returns an empty value if the environment variable does not exist. However, the function will also return an empty value if the environment variable is not set.

To solve this, we can use the LookupEnv() function. The function will retrieve the value of the environment variable if it exists and return a Boolean true. If the environment variable does not exist, the function returns an empty value and a Boolean false.

Consider the example below:

func lookup(key string) {


    _, found := os.LookupEnv(key)


    if found {


        fmt.Println(“Environmet variable found”)


    } else {


        fmt.Println(“Environemnt variable not found”)


    }

}

The example holds a function that takes the environment variable as the parameter. We then use the value of the key to check if it exists using an if statement.

If we run the above code with two parameters as shown:

lookup(“HOME”)


lookup(“NOT_THERE”)

The resulting output:

$ go run getenv.go


Environmet variable found


Environemnt variable not found

SetEnv

What if we want to set a value for a specific environment variable? In such a scenario, we can use the SetEnv() function. The function takes the key (name of the environment variable) and its associated value as the parameters.

The example below sets the value of the user shell:

func set_shell() {


    fmt.Println(“Before: “, os.Getenv(“SHELL”))


    os.Setenv(“SHELL”, “https://linuxhint.com/bin/zsh”)


    fmt.Println(“After: “, os.Getenv(“SHELL”))

}

The above example sets the value of the SHELL environment variable to “/bin/zsh”. An example output is as:

Before: /bin/bash


After: /bin/zsh

UnsetEnv

We can also unset an environment variable using the UnsetEnv() method. An example is as shown:

func unset_env() {


    fmt.Println(“HOME: “, os.Getenv(“HOME”))


    os.Unsetenv(“HOME”)


    fmt.Println(“Home: “, os.Getenv(“HOME”))

}

The example above will unset the value of the HOME env variable.

Output:

$ go run getenv.go


HOME:  C:Userscsalem // windows


Home:

Environ

The Environ() method allows you to list all the environment variables in a system. The function returns the result in the form of key-value pairs.

An example is shown below:

func list_env() {


    for _, env := range os.Environ() {


        pair := strings.SplitN(env, “=”, 2)


        fmt.Printf(“%s: %sn, pair[0], pair[1])


    }

}

The above example uses the Environ() method to list all the environment variables in the system. We then use the SplitN method to split the strings into key-value pairs.

Clearenv()

If you want to delete all the environment variables in your system, you can use the Clearenv() method.

Caution when using this method as it will reset all the env in the system.

To use it, consider the snippet below:

Expandenv

The Expandenv() allows you to replace the $var with the actual value of an environment variable inside a string. This is a very useful function when working with env.

For example:

func replace_env() {


    fmt.Println(os.ExpandEnv(“username: $USERNAME.”))

}

The function will expand the “USERNAME” environment variable and substitute its value inside the string. The result is as:

Conclusion

This guide explored the foundation of working with environment variables in the go programming language using the os package.

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2022/02/echo/john-150×150.png621352af29d08.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list