-2

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!

Hasan A Yousef
  • 19,411
  • 21
  • 113
  • 174

1 Answers1

0

Thanks to @mkopriva, 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)
}
Hasan A Yousef
  • 19,411
  • 21
  • 113
  • 174