Skip to content

Instantly share code, notes, and snippets.

@mavjs
Last active May 31, 2022 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mavjs/d6e8cc5f16cd8f55b62595e5e0723b6c to your computer and use it in GitHub Desktop.
Save mavjs/d6e8cc5f16cd8f55b62595e5e0723b6c to your computer and use it in GitHub Desktop.
Golang related cli command notes

About

If your $GOROOT is in ~/goroot and your $GOPATH is in ~/go, you want to make sure that your new go version goes to the right folder. By default the go tar file will unpack with go/ as a prefix directory, thus we want to remove that when unpacking, thus the --strip-components=1.

tar -C ~/goroot -xzvf go$VERSION.linux-amd64.tar.gz --strip-components=1

Script to update

#!/bin/bash
# set -e
set -o pipefail

FILE_DIR=$(mktemp -d -t upgover-XXXXXXXX)

echo "Entering into temporary work directory: ${FILE_DIR}"
cd "${FILE_DIR}" || exit

URL="https://golang.org"
VER_CHECK="${URL}/dl/"
DL_URL="https://dl.google.com/go/"
LATEST_FILE=$(curl -L -s "${VER_CHECK}" | grep filename | grep download | grep linux-amd64.tar.gz | head -n 1 | cut -d">" -f 3 | cut -d"<" -f 1)

echo "Latest file: ${LATEST_FILE}"

VER=$(echo "${LATEST_FILE}" | grep -oP 'go[0-9\.]+')
LATEST_VER=${VER%?}
CUR_VER=$(go version | cut -d" " -f3)

if [ "${LATEST_VER}" == "${CUR_VER}" ];
then
    echo "You are already on the latest golang version: ${CUR_VER}"
    exit 1
fi

FILE_URL="${DL_URL}${LATEST_FILE}"
CHECKSUM_URL="${FILE_URL}.sha256"
CHECKSUM_FILE="${LATEST_FILE}.sha256sum"


echo "Downloading: ${FILE_URL} at ${LATEST_FILE}"
curl -L -s -o "${LATEST_FILE}" "${FILE_URL}"
echo "Downloading checksum: ${CHECKSUM_URL} at ${CHECKSUM_FILE}"
CHECKSUM=$(curl -s "${CHECKSUM_URL}")
echo "${CHECKSUM}"  "${LATEST_FILE}" > "${CHECKSUM_FILE}"

echo "Checking hashsum ....."
STATUS=$(sha256sum -c "${LATEST_FILE}.sha256sum" | grep OK)
if [ -n "${STATUS}" ];
then 
    echo "Hashsum is good!"
else
    echo "HASHSUM IS NOT GOOD!"
    exit 1
fi

echo "Installing....."
if [ -d "/home/${USER}/goroot" ];
then
    echo "Removing goroot before upgrade"
    rm -rf "/home/${USER}/goroot"
    mkdir "/home/${USER}/goroot/"
    echo "Installing in ~/goroot"
    tar -C "/home/${USER}/goroot" -xzf "${LATEST_FILE}" --strip-components=1
else
    echo "Removing goroot before upgrade"
    rm -rf "/usr/local/go"
    echo "Installing /usr/local/"
    tar -C "/usr/local/" -xzf "${LATEST_FILE}"
fi

echo "Cleaning up temp directory at: ${FILE_DIR}"
rm -rf "${FILE_DIR}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment