在将env变量写入/ etc / enviornment文件之后,我已经尝试了go代码中的source命令。
下面是示例代码。
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"strings"
)
func main() {
address := "localhost:9090"
file, err := os.OpenFile("/etc/environment", os.O_RDWR, 0644)
defer file.Close()
if err != nil {
panic(err)
}
input, err := ioutil.ReadAll(file)
if err != nil {
log.Fatalln(err)
}
lines := strings.Split(string(input), "\n")
for i, line := range lines {
if strings.Contains(line, "HTTP_PROXY") {
lines[i] = "HTTP_PROXY=" + address
} else {
if i == (len(lines) - 1) {
lines[i] = "HTTP_PROXY=" + address
}
}
}
output := strings.Join(lines, "\n")
err = ioutil.WriteFile("/etc/environment", []byte(output), 0644)
if err != nil {
log.Fatalln(err)
}
cmd := exec.Command("bash", "-c", "source /etc/environment")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
fmt.Println("cmd=================>", cmd, err)
if err != nil {
fmt.Println(err)
}
}
它没有返回任何错误
But when i try to check my HTTP_PROXY in using env | grep -i proxy
I dont see it getting reflected.
I can only see the change is done when it restart the system or run the source command again from another termimal
Command
exec.Command("bash", "-c", "source /etc/environment")
will run a new instance ofbash
and source environment there, then that instance of bash will end and that environment will cease to exist.See here for more about how environment variables work and their attributes and how they are passed from process to process.
To make your changes to environment effective for currently running process and processes started from it you need to modify environment of that process (see os.Setenv(). You can not change environmental variables for parent process (e.g. shell) that created your process.
这是因为仅在新会话中(或如果您手动获取了环境)才重新加载环境。否则,当前外壳程序的变量将保持不变。
这会在子外壳程序中运行命令,并且其中的更改不会影响父外壳程序。因此,一旦进程退出,更改便消失了。
实际上,根本不可能更改会影响父流程的环境变量,因为更改只会影响当前/子流程,因此无法更改父流程的环境。