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?
To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces. To set a local variable, use the command " varname =value " (or " set varname =value ").
It depends on the case, if you need a variable for just one time, you can set it up using terminal. Otherwise, you can have it permanently in Bash Shell Startup Script with “Export” command. And then close the terminal window and open another one to check out if the set variable has disappeared or not.
The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.
Not sure this is ultimately what you want to do, but it does give you the result you asked for.
package main
import (
"os"
"syscall"
)
func main() {
os.Setenv("FOO", "BAR")
syscall.Exec(os.Getenv("SHELL"), []string{os.Getenv("SHELL")}, syscall.Environ())
}
This replaces the go process with a new shell with the modified environment.
You probably would want to call it as "exec APPNAME", as that will avoid having a shell in a shell.
example:
#!/bin/bash
exec go-env-setter-app
you will end up with a bash shell with the modified environment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With