Open In App

Golang – Environment Variables

Improve
Improve
Like Article
Like
Save
Share
Report

An Environment Variable is a dynamic object pair on the Operating System. These value pairs can be manipulated with the help of the operating system. These value pairs can be used to store file path, user profile, authentication keys, execution mode, etc.

In Golang, we can use the os package to read and write environment variables.

1. Set an environment variable with os.Setenv(). This method accepts both parameters as strings. It returns an error if any.

os.Setenv(key,value)  

2. Get environment variable value with os.Getenv(). This method returns the value of the variable if the variable is present else it returns an empty value.

os.Getenv(key)

3. Delete or Unset a single environment variable using os.Unsetenv() method. This method returns an error if any.

os.Unsetenv(key)

4. Get environment variable value and a boolean with os.LookupEnv(). Boolean indicates that a key is present or not. If the key is not present false is returned.

os.LookupEnv(key)

5. List all the environment variable and their values with os.Environ(). This method returns a copy of strings, of the “key=value” format.

os.Environ()

6. Delete all environment variables with os.Clearenv().

os.Clearenv()

Example 1:

Go




// Golang program to show the usage of
// Setenv(), Getenv and Unsetenv method
  
package main
  
import (
    "fmt"
    "os"
)
  
// Main function
func main() {
  
    // set environment variable GEEKS
    os.Setenv("GEEKS", "geeks")
  
    // returns value of GEEKS
    fmt.Println("GEEKS:", os.Getenv("GEEKS"))
  
    // Unset environment variable GEEKS
    os.Unsetenv("GEEKS")
  
    // returns empty string and false,
    // because we removed the GEEKS variable
    value, ok := os.LookupEnv("GEEKS")
  
    fmt.Println("GEEKS:", value, " Is present:", ok)
  
}


Output:

Example 2:

Go




// Golang program to show the
// usage of os.Environ() Method
package main
  
import (
    "fmt"
    "os"
)
  
// Main function
func main() {
  
    // list all environment variables and their values
    for _, env := range os.Environ() {
        fmt.Println(env)
    }
}


Output:

Example 3:
 

Go




// Golang program to show the
// usage of os.Clearenv() Method
package main
  
import (
    "fmt"
    "os"
)
  
// Main function
func main() {
  
    // this delete's all environment variables
    // Don't try this in the home environment,
    // if you do so  you will end up deleting
    // all env variables
    os.Clearenv()
  
    fmt.Println("All environment variables cleared")
  
}


Output:

All environment variables cleared


Last Updated : 04 Feb, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads