Unset an environment variable

572 views
Skip to first unread message

Larry Clapp

unread,
Sep 19, 2014, 3:56:40 PM9/19/14
to golan...@googlegroups.com
Hi, Gophers.

I see how to set and query individual environment variables.  I see you can clear the entire environment.  Is there nothing in the standard library to unset a single variable?  Do I really have to copy the environment, clear it, and then reset everything but the thing I want unset?

</whine>  :)

-- Larry

Ian Lance Taylor

unread,
Sep 19, 2014, 4:08:45 PM9/19/14
to Larry Clapp, golang-nuts
On Fri, Sep 19, 2014 at 12:56 PM, Larry Clapp <la...@theclapp.org> wrote:
>
> I see how to set and query individual environment variables. I see you can
> clear the entire environment. Is there nothing in the standard library to
> unset a single variable? Do I really have to copy the environment, clear
> it, and then reset everything but the thing I want unset?

http://golang.org/issue/6423

Ian

Larry Clapp

unread,
Sep 19, 2014, 4:30:57 PM9/19/14
to golan...@googlegroups.com, la...@theclapp.org
Thank you, I did not think to search for an existing issue.

Nor did I think of filtering the environment directly when forking, as mentioned in the issue.

Sorry for the whine.

For posterity, this worked for me, though it does suffer from the same race condition mentioned in the linked issue: some other thread could read the environment after you've cleared it and and before you repopulate it.

func Unsetenv(key string) {
   
if _, found := syscall.Getenv(key); !found {
     
return
   
}
   env
:= os.Environ()
   os
.Clearenv()
   
for _, s := range env {
     
for j := 0; j < len(s); j++ {
         
if s[j] == '=' {
            k
:= s[:j]
           
if key == k {
               
break
           
}
            os
.Setenv(k, s[j+1:])
         
}
     
}
   
}
}

-- Larry

Reply all
Reply to author
Forward
0 new messages