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

时间:2016-03-18 02:01:07

标签: 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 main() {
fmt.Println(os.Getenv("WHAT"))
os.Setenv("WHAT", "is your name")
fmt.Println(os.Getenv("WHAT"))
}

由于

3 个答案:

答案 0 :(得分:5)

不,环境变量只能传递,而不能传递。你试图做后者。

您的流程树:

`--- 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

答案 1 :(得分:1)

没有

流程包含其父级环境的副本,无法写入父级环境。

答案 2 :(得分:0)

其他答案完全正确,但是您可以自由执行golang代码以将环境变量的任意值填充到go创建的输出文件中,然后返回执行的父环境,该二进制文件是go的源代码,然后为go的源代码输出文件,其中包含从go代码内部计算出的可用env变量...这可能是go代码write_to_file.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.go上面的代码编译为二进制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

这是上面的shell脚本执行后的输出

variable whodunit has value aaa
variable whodunit finally has value calculated_in_golang