How to Set the GOPATH Environment Variable on Ubuntu?

In Ubuntu, Go is an open-source programming language officially invented by Google. It is utilized by developers for developing project applications such as web server, management systems, etc. However, the user needs to set the GOPATH environment variable to run the codes of the projects in the specified project directory.

This post will cover the step-by-step guide for setting the GOPATH environment variable on Ubuntu.

  • Prerequisite: Install Go on Ubuntu
  • Set the GOPATH Environment Variable

Prerequisite: Install Go on Ubuntu

Before setting the GOPATH environment variable, the Go application must be installed in the system. For the installation of Go in Ubuntu, explore our latest guide here.

Set the GOPATH Environment Variable

The user can set the GOPATH environment variable in the “.bashrc” file so that it will be auto-assigned to the project when the user logged in. To set the GOPATH environment variable, go through the following steps:

Step 1: Create the Project Directory 

First, create the project directory named “Go_Project” for the application project or users can determine if the project directory already exists:

$ mkdir Go_Project

The “Go_Project” directory has been created.

Step 2: Configure “.bashrc” File

The next step is to configure the “.bashrc” file and export the path of the project directory as shown in the below syntax:

Syntax: 

export GOPATH=$HOME/<Directory>

Specify the project directory in the <Directory> as in our case, the directory is “Go_Project”:

$ nano .bashrc                      #Opens the .bashrc file export GOPATH=$HOME/Go_Project

Save the file by pressing “Ctrl+O” and exit from the file by pressing “Ctrl+X”.

Step 3: Execute the “.bashrc” File

Now, execute the “.bashrc” file to apply the changes in the current bash session:

$ source .bashrc

The “.bashrc” file is executed.

Step 4: Verify the Path

The user can verify the path of the environment variable “$GOPATH” through the echo command: 

$ echo $GOPATH

The environment variable “GOPATH” is set to the directory “/home/itslinuxfoss/Go_Project

Conclusion

In Ubuntu, the environment variable GOPATH is set by exporting the project directory path through the export command in the “.bashrc” file. The users can use the syntax “export GOPATH=$HOME/<Directory>” with their project directory name. To verify the path of the environment variable, execute the “echo $GOPATH” command.

This write-up has illuminated the step-by-step guide for setting the GOPATH environment variable in Ubuntu.