Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables. |
|
package main
|
|
import "os"
import "strings"
import "fmt"
|
|
func main() {
|
|
To set a key/value pair, use |
os.Setenv("FOO", "1")
fmt.Println("FOO:", os.Getenv("FOO"))
fmt.Println("BAR:", os.Getenv("BAR"))
|
Use |
fmt.Println()
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
fmt.Println(pair[0])
}
}
|
Running the program shows that we pick up the value
value for |
$ go run environment-variables.go
FOO: 1
BAR:
|
The list of keys in the environment will depend on your particular machine. |
TERM_PROGRAM
PATH
SHELL
...
|
If we set |
$ BAR=2 go run environment-variables.go
FOO: 1
BAR: 2
...
|
Previous example: Command-Line Flags.
Next example: Spawning Processes.