Go – Problems with environment variables in go

environment-variablesgo

I was trying to run go install on my .go files however, it seems to fail. It fails because my GOBIN environment variable is not set. However, when I echo it I do get that its set because my .bashrc and .bash_profile files make sure its set. However, it is not set in go env. For some reason go doesn't recognize its set when it actually is set.

However, if I manually set on my shell as:

me$ export GOBIN=$GOBIN

now go env decides to recognize it, eventhough I have the explicit line on my .bashrc file exporting it and my echo confirms that its set. Does someone know why go is acting strange?

Things that I have tried/Reference

My Operating system

mac osx mavericks.

GO VERSION

-my go version is go version go1.2 darwin/386. When I run

go version

I get:

go version go1.2 darwin/386

What go env recognizes and environment variables

Running

go env

displays in my terminal:

GOARCH="386"
GOBIN=""
GOCHAR="8"
GOEXE=""
GOHOSTARCH="386"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH=""
GORACE=""
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_386"
TERM="dumb"
CC="gcc"
GOGCCFLAGS="-g -O2 -fPIC -m32 -pthread -fno-common"
CXX="g++"
CGO_ENABLED="1"

How my .bashrc and .bash_profile look like

I am sourcing my .bashrc file in my .bash_profile. I.e. here this piece of code in my .bash_profile:

if [ -f ~/.bashrc ]; then
  source ~/.bashrc #executes for bash subshells
fi

I have also tried to manually (by manually I mean typing it on the bash explicitly as a human) source my .bash_profile (since that will run my .bashrc file anyway) and go env still fails to recognize it.

Only when I literally type in my shell

me$ export GOBIN=$GOBIN

does go env return what I want:

GOARCH="386"
GOBIN="/Users/brando90/go/bin"
GOCHAR="8"
GOEXE=""
GOHOSTARCH="386"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH=""
GORACE=""
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_386"
TERM="dumb"
CC="gcc"
GOGCCFLAGS="-g -O2 -fPIC -m32 -pthread -fno-common"
CXX="g++"
CGO_ENABLED="1"

Best Answer

Try this in your relevant shell profile:

export GOPATH=/path/to/your/go/workspace
export PATH=$GOPATH/bin:$PATH

Don't set GOBIN as it's not useful for 99% of cases (i.e. single user machines; see the cmd docs). Make sure to unset GOBIN after making these changes.

Go will know where to install binaries as GOPATH/{bin, pkg, src} is something Go handles for you. Your shell, on the other hand, needs to know to add $GOPATH/bin to your path so you can run Go binaries directly.