Golang os getenv: Environment Variables in Go

Golang os.getenv() method is “used to retrieve an environment variable’s value by the key”. It will return an empty string if the key is not in the environment.

An environment variable is a “mechanism for provisioning dynamic configuration information to Unix programs at runtime”. Golang environment variables are global variables set outside of the program and can be accessed by the program at runtime.

Syntax

func Getenv(key string) string

Parameters

key: It is a string.

Return value

It returns the value based on the provided key. It returns an empty value if the variable is not present.

Example: Usage of os.getenv()

package main

import (
  "fmt"
  "os"
)

func main() {
  current_user := os.Getenv("USER")
  fmt.Println("The current user is:", current_user)

  // Retrieve the value of the "SHELL" environment variable
  shell := os.Getenv("SHELL")
  fmt.Println("The current shell is:", shell)
}

Output

The current user is: krunallathiya
The current shell is: /bin/zsh

You can see that inside the main() function, we first retrieved the current user’s name from the environment variable USER and printed it.

In the next step, we fetched the shell path set in the SHELL environment variable and displayed this information.

The os.Getenv() function is used to access the environment variables and the fmt.Println() function to print out the values.

Key points

  1. To set a key/value pair, use the “os.Setenv()” function.
  2. To get a value for a key, use “os.Getenv()”.
  3. Use the os.Environ() function to list all key/value pairs in the environment.

That’s it.