Skip to content

Instantly share code, notes, and snippets.

@bitkidd
Last active July 20, 2017 21:39
Show Gist options
  • Save bitkidd/995c0b059379ba6f5066aba3167270b4 to your computer and use it in GitHub Desktop.
Save bitkidd/995c0b059379ba6f5066aba3167270b4 to your computer and use it in GitHub Desktop.
Manage multiple GOPATH dirs with ease

The solution is simple. Just include the following snippet in your ~/.bashrc (or ~/.bash_profile) and reload your shell environment with source ~/.bashrc. This snippet will create a shell function that will override the builtin command cd with a customized one that scans the entered directory, and every other above, for a file named .gopath.

cd () {
    builtin cd "$@"
    cdir=$PWD
    while [ "$cdir" != "/" ]; do
        if [ -e "$cdir/.gopath" ]; then
            export GOPATH=$cdir #or GOPATH=$GOPATH:$cdir if you want to keep original $GOPATH
            break
        fi
        cdir=$(dirname "$cdir")
    done
}

Now you just need to create a .gopath file in every directory you want as your GOPATH and every time you enter this directory, the redefined cd function will set the GOPATH of your current environment to this directory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment