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
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
No.
A process has a copy of its parent's environment and can't write to the parent environment.
The other answers are strictly correct, however you are free to execute your golang code to populate arbitrary values to environment variables into an output file your go creates then back in the parent environment from which you executed that go binary then source the go's output file to have available env variables calculated from inside your go code ... this could be your go code write_to_file.go
package main
import (
"io/ioutil"
)
func main() {
d1 := []byte("export whodunit=calculated_in_golang
")
if err := ioutil.WriteFile("/tmp/cool_file", d1, 0644); err != nil {
panic(err)
}
}
now compile above write_to_file.go into binary write_to_file
... here is a bash script which can act as the parent to execute above binary
#!/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
here is the output from executing above shell script
variable whodunit has value aaa
variable whodunit finally has value calculated_in_golang