How do I SET the PATH environment variable from Go?

I know how to do it on the command line:

Windows:
setx PATH "D:\Programming;%PATH%"

Linux:
export PATH=$PATH:/Home/Programming

But how do I do it from a Go program? The changes must be persistent.

Define “persistent”.

Generally any changes to the environment only affect the process itself and it’s children.

As soon as the process exits, all changes to the environment are forgotten.

1 Like

I meant permanent, that the changes are retained even after the program ends.

I have done some tests but unfortunately the PATH always ends up dirty with folders that should not be there, I know why that happens but I don’t know how to avoid it.

My goal is to make them work on Linux and Windows, similar to how Go modifies the PATH variable when it is first installed, Go does it without damaging any of the original PATH content and just adds its new path.

Totally depends on how you install go, though probably whatever you used, just changed your shells RC files.

Some common behaviour among installers…

It’s gross to do so without asking…

go env -w ENV_VAR=value

This is a cross-platform solution built into the go CLI that should save you some time in the future.

  • Example: go env -w GOPATH=/your/desired/path

go env to check your current environment configuration or go env GOPATH.

1 Like

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