在设置“os”后,终端会话中未设置环境变量。包 [英] Environment variable is not set on terminal session after setting it with "os" package

查看:139
本文介绍了在设置“os”后,终端会话中未设置环境变量。包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

fmt.Println 调用打印 BAR 正确,但我希望这个env变量可以在我的会话中设置,但是:

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

>$

$ FOO ,它是空的。这是一个预期的行为?如果是这样,我该如何让这个env变量在我的会话中持久保存,像这样使用 go 程序?

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?

推荐答案

创建新进程时,会复制父进程的环境。新进程中环境的更改不会影响父进程。修改环境后,您必须让程序启动一个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.

这篇关于在设置“os”后,终端会话中未设置环境变量。包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆