环境变量在使用“os”包设置后,在终端会话中未设置

huangapple go评论71阅读模式
英文:

Environment variable is not set on terminal session after setting it with "os" package

问题

我有这样一段代码,我只想设置一个环境变量:

package main

import (
	"os"
	"fmt"
)

func main() {
	_ = os.Setenv("FOO", "BAR")
	fmt.Println(os.Getenv("FOO"))
}

运行这个文件:

>$ go run file.go
BAR

fmt.Println 调用正确地打印了 BAR,但是我期望这个环境变量也能在我的会话中设置,然而:

>$ echo $FOO

>$

$FOO 上没有任何内容,它是空的。这是预期的行为吗?如果是,我该如何使这个环境变量在我的会话中持久化,像这样用 go 程序设置它?

英文:

I have this code where I just want to set a environment variable:

package main

import (
	"os"
    "fmt"
)

func main() {
	_ = os.Setenv("FOO", "BAR")
    fmt.Println(os.Getenv("FOO"))
}

Running this file:

>$ go run file.go
BAR

The fmt.Println call prints BAR correctly, but then I expected this env variable to be set on my session as well, however:

>$ echo $FOO

>$

There's nothing on $FOO, it is empty. Is this a expected behavior? If so, how can I make this env variable to persist on my session setting it with a go program like this?

答案1

得分: 18

当创建一个新的进程时,父进程的环境会被复制。在新进程中对环境的更改不会影响到父进程。如果你想要在修改环境后生效,你需要让你的程序在修改环境后启动一个shell。

英文:

When a new process is created, the environment of the parent process is copied. Changes to the environment in the new process do not affect the parent process. You would have to have your program start a shell after modifying the environment.

答案2

得分: 13

不确定这最终是否是你想要做的,但它确实给出了你要求的结果。

package main
import (
        "os"
        "syscall"
)
func main() {
        os.Setenv("FOO", "BAR")
        syscall.Exec(os.Getenv("SHELL"), []string{os.Getenv("SHELL")}, syscall.Environ())
}

这将用修改后的环境替换go进程为一个新的shell。

你可能想要将其调用为"exec APPNAME",这样可以避免在一个shell中再次运行shell。

示例:

#!/bin/bash
exec go-env-setter-app

你将得到一个具有修改后环境的bash shell。

英文:

Not sure this is ultimately what you want to do, but it does give you the result you asked for.

package main
import (
        "os"
        "syscall"
)
func main() {
        os.Setenv("FOO", "BAR")
        syscall.Exec(os.Getenv("SHELL"), []string{os.Getenv("SHELL")}, syscall.Environ())
}

This replaces the go process with a new shell with the modified environment.

You probably would want to call it as "exec APPNAME", as that will avoid having a shell in a shell.

example:

#!/bin/bash
exec go-env-setter-app

you will end up with a bash shell with the modified environment

huangapple
  • 本文由 发表于 2013年6月28日 23:31:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/17368392.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定