os.GetEnv() dosen't work after set env variable

14,147

Solution 1

I think the problem is likely that you are not exporting the variable, so the sub process (i.e. you ide, shell, is not getting it).

ADDR="192.168.1.100" go run main.go

or

export ADD="192.168.1.100"
go run main.go

Solution 2

I had same problem and for me it's because I run the program with sudo.

I checked the environment variable as a normal user. But run the program as root. So their environment could not be the same.

Share:
14,147
Mbded
Author by

Mbded

Updated on July 20, 2022

Comments

  • Mbded
    Mbded almost 2 years

    I have the case dosen't work function

    os.GetEnv()

    I have set a variable in my system ADDR="192.168.1.100" trought file .bashrc and .profile. So if I open terminal and type below command, I get good result

    $ echo $ADDR

    192.168.1.100

    Why in below very simply program I get Error if variable is correct set in system ?

    func main(){
        addr := os.Getenv("ADDR")
        if addr == "" {
            return errors.New("missing addres")
        }
    }
    

    I also restarted IDE a many times. Tried write in terminal again

    $ env ADDR="192.168.1.100"

    but still this same effect.