Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist the value set for an env variable on the shell after the go program exits

Tags:

go

Is there a way i can set an Environment variable on my shell and have it persist after the go program exits ? I tried the following

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$ 

The code was :

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

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

Thanks

like image 311
kbinstance Avatar asked Dec 19 '22 18:12

kbinstance


1 Answers

No, environment variables can only be passed down, not up. You're trying to do the latter.

Your process tree:

`--- shell
          `--- go program
          |
          `--- other program

The go program would have to pass the environment variable up to the shell so that the other program can access it.

What you can do is what programs like ssh-agent do: return a string that can be interpreted as setting a environment variable which can then be evaluated by the shell.

For example:

func main() {
    fmt.Println("WHAT='is your name'")
}

Running it will give you:

$ ./goprogram
WHAT='is your name'

Evaluating the printed string will give you the desired effect:

$ eval `./goprogram`
$ echo $WHAT
is your name
like image 142
nemo Avatar answered Feb 23 '23 00:02

nemo