Home >Backend Development >Golang >How Can I Make Environment Variable Changes Persistent Across Processes in Go?
An attempt to set an environment variable using the "os" package in a Go program persists within the program, but not in the terminal session.
When a new process is created in a system, it inherits a copy of its parent process's environment variables. However, changes made to these variables within the child process do not propagate back to the parent process.
To ensure the environment variable persists beyond the current program execution, the program can launch a new shell (or terminal session) with the modified environment variables. This can be achieved by using the os.StartProcess function with appropriate command line arguments.
The following code snippet demonstrates how to set an environment variable using the "os" package and launch a new shell with the modified environment:
package main import ( "fmt" "os" "os/exec" ) func main() { // Set the environment variable _ = os.Setenv("FOO", "BAR") // Build the command to launch a new shell cmd := exec.Command("sh", "-c", "env") cmd.Env = os.Environ() // Launch the shell with the modified environment err := cmd.Run() if err != nil { fmt.Println("Failed to launch shell:", err) return } // Print the environment variable value within the new shell stdout, err := cmd.Output() if err != nil { fmt.Println("Failed to get shell output:", err) return } fmt.Println(string(stdout)) }
Running the above program will create a new shell session with the updated environment variable and print its value.
The above is the detailed content of How Can I Make Environment Variable Changes Persistent Across Processes in Go?. For more information, please follow other related articles on the PHP Chinese website!