登录
首页 >  Golang >  Go问答

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

来源:Golang技术栈

时间:2023-04-14 09:17:26 322浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《Environment variable is not set on terminal session after setting it with "os"package》将会介绍到golang等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

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?

正确答案

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.

好了,本文到此结束,带大家了解了《Environment variable is not set on terminal session after setting it with "os"package》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>