In a Go program, setting an environment variable using the "os" package affects the program's environment, but the variable is not set in the current terminal session.
package main import ( "os" "fmt" ) func main() { _ = os.Setenv("FOO", "BAR") fmt.Println(os.Getenv("FOO")) }
Running the program prints "BAR" as expected, indicating that the environment variable was set for the program. However, when checking the environment variable in the terminal using the echo command, it remains empty.
When a new process is created, it inherits a copy of the parent process's environment. Any changes made to the environment in the new process do not propagate back to the parent process.
To make the environment variable persist in the current terminal session, the program needs to spawn a new shell after modifying the environment. This can be achieved using the exec package:
package main import ( "os/exec" ) func main() { _ = os.Setenv("FOO", "BAR") // Spawn a new shell with the updated environment cmd := exec.Command("bash") cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr // Start the shell err := cmd.Start() if err != nil { fmt.Println(err) return } // Wait for the shell to terminate err = cmd.Wait() if err != nil { fmt.Println(err) return } }
Now, running this program will set the environment variable "FOO" to "BAR" in the current terminal session.
The above is the detailed content of Why Doesn\'t Setting an Environment Variable in Go Persist in My Terminal Session?. For more information, please follow other related articles on the PHP Chinese website!