Golang : Set, Get and List environment variables
Environment variables allow Unix programs to store configuration information and the program behaviour maybe altered if the environment variables related to the program changed during runtime. Golang os package allows a Go program to set, get and list the environment variables.
This example below will show you how to set the environment variables, get them and list them.
package main
import (
"fmt"
"os"
"strings"
)
func main() {
// set environment variable example
os.Setenv("testvar", "123")
testvar := os.Getenv("testvar")
fmt.Printf("testvar value is %v", testvar)
// what happened if try to get a non existence environment variable
fmt.Println(os.Getenv("testnone")) // just return empty string
// list out the
var env []string
env = os.Environ()
fmt.Println("List of Environtment variables : \n")
for index, value := range env {
name := strings.Split(value, "=") // split by = sign
fmt.Printf("[%d] %s : %v\n", index, name[0], name[1])
}
}
Sample output(depending on your machine) :
testvar value is 123
List of Environtment variables :
[0] TERM_PROGRAM : iTerm.app
[1] SHELL : /bin/bash
[2] TERM : xterm-256color
[3] TMPDIR : /var/folders/nd/5m9x1v_j4338y_t1rg02zbph0000gn/T/
...
[18] LC_CTYPE : UTF-8
[19] _ : /usr/local/go/bin/go
[20] testvar : 123
To set value for testnone
variable, you can do it in the command line :
export testnone=456
and the result from executing the same code again will look like this :
testvar value is 123456 (456 is the testnone variable)
List of Environtment variables :
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+16.4k Golang : Test floating point numbers not-a-number and infinite example
+10.2k Golang : Detect number of faces or vehicles in a photo
+10.5k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+14.7k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+13.4k Golang : Count number of runes in string
+23.4k Golang : Get ASCII code from a key press(cross-platform) example
+5.8k Golang : Detect variable or constant type
+8.4k Golang : Generate Datamatrix barcode
+19.2k Golang : Get host name or domain name from IP address
+20.1k Golang : Convert seconds to human readable time format example
+22.1k Golang : Match strings by wildcard patterns with filepath.Match() function
+50.9k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate