在go程序退出后,在shell上保留为env变量设置的值

在go程序退出后,在shell上保留为env变量设置的值,go,Go,有没有办法在shell上设置一个环境变量,并在go程序退出后将其持久化?我尝试了以下方法 bash-3.2$ export WHAT=am bash-3.2$ echo $WHAT am bash-3.2$ go build tt.go bash-3.2$ ./tt am is your name bash-3.2$ echo $WHAT am bash-3.2$ 代码是: package main` import ( "fmt" "os"` ) func

有没有办法在shell上设置一个环境变量,并在go程序退出后将其持久化?我尝试了以下方法

bash-3.2$ export WHAT=am
bash-3.2$ echo $WHAT
am

bash-3.2$ go build tt.go 
bash-3.2$ ./tt
am
is your name
bash-3.2$ echo $WHAT
am
bash-3.2$ 
代码是:

package main`
import (
        "fmt"
       "os"`
)

func main() {
fmt.Println(os.Getenv("WHAT"))
os.Setenv("WHAT", "is your name")
fmt.Println(os.Getenv("WHAT"))
}

谢谢

不,环境变量只能向下传递,不能向上传递。你在尝试做后者

您的流程树:

`--- shell
          `--- go program
          |
          `--- other program
go程序必须将环境变量传递给shell,以便其他程序可以访问它

您可以做的是像
ssh-agent
这样的程序所做的:返回一个字符串,该字符串可以解释为设置一个环境变量,然后由shell对其进行计算

例如:

func main() {
    fmt.Println("WHAT='is your name'")
}
运行它将为您提供:

$ ./goprogram
WHAT='is your name'
评估打印字符串将获得所需的效果:

$ eval `./goprogram`
$ echo $WHAT
is your name
没有


进程有其父环境的副本,无法写入父环境。

其他答案完全正确,但是,您可以自由执行golang代码,将环境变量的任意值填充到go创建的输出文件中,然后返回到执行go二进制的父环境中,然后将go的输出文件源化,以便从go代码内部计算可用的环境变量。。。这可能是您的go代码写入文件。go

package main

import (
    "io/ioutil"
)

func main() {

    d1 := []byte("export whodunit=calculated_in_golang\n")
    if err := ioutil.WriteFile("/tmp/cool_file", d1, 0644); err != nil {
        panic(err)
    }
}
现在编译上面的write_to_file。进入二进制
write_to_file
。。。下面是一个bash脚本,它可以作为执行上述二进制代码的父脚本

#!/bin/bash

whodunit=aaa

if [[ -z $whodunit ]]; then

    echo variable whodunit has no value
else

    echo variable whodunit has value $whodunit
fi

./write_to_file # <-- execute golang binary here which populates an exported var in output file /tmp/cool_file

curr_cool=/tmp/cool_file

if [[ -f $curr_cool ]]; then # if file exists

    source /tmp/cool_file # shell distinguishes sourcing shell from executing, sourcing does not cut a subshell it happens in parent env
fi

if [[ -z $whodunit ]]; then

    echo variable whodunit still has no value 
else

    echo variable whodunit finally has value $whodunit
fi

@备忘录的答案比我的更详细,接受他的。好的。我懂了。我有没有办法在go程序中生成一个shell进程,在其中设置变量,运行任何函数,然后在完成后退出该进程?我有一些测试依赖于设置的一些环境变量。然而,我的项目中的其余测试需要这些变量的不同值。因此,我试图找出如何最好地处理这种情况,以便我仍然可以运行go测试。/。。。而且没有任何测试失败。当然。查看
os/exec
软件包并使用
/bin/sh-c'
@kbinstance为了回答您提出的所有其他问题,请将帮助您解决问题的答案标记为已接受(选中答案投票按钮下方的复选标记)。谢谢
variable whodunit has value aaa
variable whodunit finally has value calculated_in_golang