Creating Env variable

At my Windows 11 machine, trying to check if the env variable “” exists or no, if yes, I need to read its value, if not there I need to set it, so I wrote the below code:

	tmpDir, exists := os.LookupEnv("keyTemp")
	fmt.Println("keyTemp: ", exists)
	fmt.Println("tmpDir: ", tmpDir)
	if !exists {
		tmpDir = os.TempDir() + "\\fitz"
		fmt.Println("tmpDir: ", tmpDir)
		err = os.Setenv("keyTemp", tmpDir)
		if err != nil {
			panic(err)
		}
	}

But always (after rerunning the binary) I’m getting the “exists” value as false and my env variable is never created!

It looks no direct way at go lang itself, so the option is to use cmd, so it worked with me as:

tmpDir = os.TempDir() + "\\fitz"
// err = os.Setenv("keyTemp", tmpDir)
err = exec.Command(`SETX`, `keyTemp`, tmpDir).Run()
if err != nil {
	fmt.Printf("Error: %s\n", err)
}

“created” in what sense?

Environment variables set by a process are only visible to a process and it’s children, not to siblings or parents.

1 Like

Usually environment variables created by a process are visible only by the process itself and its children.
In this case it’s normal you can’t see the variable that your program creates

1 Like

Your code is fine. The SETX command is the only way to create system environment values.

1 Like

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