Home »
Golang »
Golang Reference
Golang os.Getenv() Function with Examples
Golang | os.Getenv() Function: Here, we are going to learn about the Getenv() function of the os package with its usages, syntax, and examples.
Submitted by IncludeHelp, on November 18, 2021
os.Getenv()
In the Go language, the os package provides a platform-independent interface to operating system (Unix-like) functionality. The Getenv() function is an inbuilt function of the os package, it is used to get the value of the environment variable specified by the key. It returns the value, which will be empty if the variable is not present.
It accepts one parameter (key string) and returns a string containing the value of the given environment variable, it may also be empty if the variable is not present.
Syntax
func Getenv(key string) string
Parameters
- key - Environment variable whose value is to be found.
Return Value
The return type of the os.Getenv() function is a string, it returns the value, which will be empty if the variable is not present.
Example 1
// Golang program to demonstrate the
// example of Getenv() function
package main
import (
"fmt"
"os"
)
func main() {
// Getting & printing the values of
// PATH, HOSTNAME and HOME
fmt.Println("PATH:", os.Getenv("PATH"))
fmt.Println("HOSTNAME:", os.Getenv("HOSTNAME"))
fmt.Println("HOME:", os.Getenv("HOME"))
}
Output:
PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME: ef1235acfac8
HOME: /root
Example 2
// Golang program to demonstrate the
// example of Getenv() function
package main
import (
"fmt"
"os"
)
func main() {
// Setting the custom variables/fields
os.Setenv("NAME", "Alvin")
os.Setenv("EXAMPLE_PATH", "/root/Alvin/Examples")
// Getting & printing the values of
// NAME, and EXAMPLE_PATH
fmt.Println("NAME:", os.Getenv("NAME"))
fmt.Println("EXAMPLE_PATH:", os.Getenv("EXAMPLE_PATH"))
}
Output:
NAME: Alvin
EXAMPLE_PATH: /root/Alvin/Examples
Golang os Package »