Modify environment variables in the program, why will the next modification not take effect in the actual terminal environment?

  golang, question

I wrote a simple command line tool, the purpose of this tool is to rewrite the system environment variables (such asGOPATH), the specific implementation isos.Setenv("GOPATH", xxxx). Why did I execute this program under the terminal, afterUnder the same terminal, the modified environment variables have not been really modified? What is the principle behind this? Curious.Environment Variables in ProgramsYesActual environment variableA copy of? Or is it that,Environment Variables in ProgramsYesActual environment variableTheBashAnd has not beenexport? Ha ha, if you know, just let me know.

Environmental variables are related toProcessCorrespondingly, the process inherits (can be understood as copying) all the environment variables of its parent process at the beginning. After that, the process’s modification of the environment variables will not affect the parent process, and its environment variables will be completely cleared at the end of the process.

When your tool is running, the parent process is what you call a terminal.os.SetenvWhat is modified is the environment variable of the tool process, and the environment variable of the terminal process cannot be modified, so when the tool process exits, the environment variable of the terminal process remains the same.

Or is the environment variable in the program a child bash of the actual environment variable and has not been export?

There is no so-called “sub bash” when your tool process is running (unless explicitly calledos/execSome of the methods of),exportOnly the environment variables of the current bash process have been modified, but the commands invoked by bash are all created as its child processes, so the commands subsequently invoked will inherit its environment variables.