Export environment variables using Go program not working in bash

I’m a beginner to go and i’m trying to write a program to set the environment values using go code. The env value should be visible when i run export command in bash terminal after executing the go code.

When i run the program it ran successfully os.Getenv and os.Setenv but when i run “export” command (after code execution exits) in shell to see the environment variable “KEY_ID” / “SECRET_ID” and its values i dont see it.

Example code:

package main

import (

func main() {
var err error
if err != nil {
os.Setenv(“KEY_ID”, “Hello”)
os.Setenv(“SECRET_ID”, “world”)

after this i ran “export” command in terminal window to see the key “KEY_ID” & “SECRET_ID” are exist but i dont see it.

Please advise where i’m wrong and how to achieve it.

This is not possible. You can not set the environment of your parents.

What you could do is to print a bash script to the programs stdout and use use bash’s builtin eval to evcaluate that script:

package main

import "fmt"

func main() {
  fmt.Println("export KEY_ID=Hello")
  fmt.Println("export SECRET_ID=world")
$ eval $(go run main.go)
$ printenv KEY_ID
$ printenv SECRET_ID
1 Like

Thanks Nobbz. I wanted to achieve it through go code. Can i run this command eval $(go run main.go) through go?. Hope that will not work right?

No. As I said, you can not alter your parent processes environment.

The only way to come close to what you want is to print a script which you eval in the parent as shown.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.