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
- To set a key/value pair, use the “os.Setenv()” function.
- To get a value for a key, use “os.Getenv()”.
- Use the os.Environ() function to list all key/value pairs in the environment.
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.