-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
  • 22,789
  • 24
  • 132
  • 203
  • 1
    What do you mean by always? Are you running the code in a loop? Or are you re-running the binary? If the latter then the answer is obvious, you'd need to persist the env var somehow (~/.bashrc, or ~/.profile, etc..) and reload the env before re-running the binary. – mkopriva Jul 30 '21 at 11:17
  • @mkopriva rerunning the binary – Hasan A Yousef Jul 30 '21 at 11:18
  • @mkopriva How can I persist the env var? – Hasan A Yousef Jul 30 '21 at 11:20
  • I'm not sure with Windows, but [this](https://stackoverflow.com/a/5898184/965900) seems to me to be what you're looking for. – mkopriva Jul 30 '21 at 11:33

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
  • 22,789
  • 24
  • 132
  • 203