Golang os getenv: Environment Variables in Go

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.

Golang os.getenv() is a built-in function that “retrieves an environment variable’s value by the key”. It will return an empty string if the key is not in the environment.

Syntax

func Getenv(key string) string

Parameters

It takes a key as an argument which 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

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

In this example, the os.Getenv() function fetches the values of the USER and SHELL environment variables, which are then printed to the console using the fmt.Println() function.

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.

Leave a Comment