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

后端 未结 2 726
忘掉有多难
忘掉有多难 2020-12-30 10:26

I have this code where I just want to set a environment variable:

package main

import (
    \"os\"
    \"fmt\"
)

func main() {
    _ = os.Setenv(\"FOO\", \         


        
2条回答
  •  萌比男神i
    2020-12-30 11:19

    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

提交回复
热议问题