Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Install Go on Linux

Go

In order to install go on Linux, copy, paste, and execute the following command:

curl -s https://scripts.programster.org/scripts/15?output=raw | bash

... or copy, paste, and execute the following script:

#!/bin/bash
if ! [ -n "$BASH_VERSION" ];then
    echo "this is not bash, calling self with bash....";
    SCRIPT=$(readlink -f "$0")
    /bin/bash $SCRIPT
    exit;
fi

cd $HOME

# Download and extract Go for linux
VERSION="1.7"
curl -O https://storage.googleapis.com/golang/go$VERSION.linux-amd64.tar.gz
tar --extract --gzip --file go$VERSION.linux-amd64.tar.gz

# /usr/local/go is the officially-recommended location
sudo chown -R root:root ./go
sudo mv go /usr/local

# Create the local directory for go projects
mkdir -p $HOME/work/src

# Set up go paths
echo 'export GOPATH=$HOME/work' >> ~/.profile 
echo 'export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin' >> ~/.profile

You will need to log out and in again, or run source $HOME/.profile in order to start using the go commands.

All your go projects need to be in folders under $HOME/work/src in order to be compiled easily.

HelloWorld

Lets create, build, and execute a hello world application. First lets create our project folder:

mkdir -p $HOME/work/src/hello

Now create our source code:

editor $HOME/work/src/hello/hello.go

Fill it with the following contents:

package main

import "fmt"

func main() {
    fmt.Printf("hello, world\n")
}

Compile and install the application:

go install hello

Execute the application:

hello

You should get the output:

hello, world

The hello application (along with any others you build) will be located under: $HOME/work/bin/ which you will see by executing:

which hello

References

Last updated: 16th August 2018
First published: 16th August 2018

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch