Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment variable is not set on terminal session after setting it with "os" package

Tags:

go

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?

like image 343
Fernando Á. Avatar asked Jun 28 '13 15:06

Fernando Á.


People also ask

How do I set an environment variable in terminal?

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 ").

How do I set environment variables in terminal Mac?

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.

How do I set environment variable in terminal bash?

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.


1 Answers

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

like image 87
David Budworth Avatar answered Oct 18 '22 17:10

David Budworth