茶蜂 danger: high entropy

A script for keeping go up to date on Linux

go code

I use the following script to keep go up to date on my local machine without using a package manager. This is by no means elegant or efficient, but it gets the job done. It finds the current version of go by scraping the go.dev website with a very naive match, and then plops the resulting tarball onto my filesystem.

Raw link: getgoer.sh

#!/bin/zsh

## Usage:
## getgoer [install]
## getgoer alone will output the current and remote versions
## getgoer install will upgrade if the current vesrsion is different than the remote version

arch="linux-amd64"

function getLinks() {
    curl https://go.dev/dl/ 2>/dev/null | awk '/download downloadBox(.*)/ {match($0, /href="(\/dl\/go([0-9]+\.[0-9]+\.[0-9]+)\.([^.]+)\..+)"/, arr); print arr[1]}'
}

links=$(getLinks)

function remoteVersion() {
    echo $links | awk -v arch="${arch}" '$0~arch {match($1, /\/dl\/go([0-9]+\.[0-9]+\.[0-9]+)/, arr); print arr[1]}'
}

function installedVersion() {
    go version | awk '{match($0, /go([0-9]+\.[0-9]+\.[0-9]+)/, arr); print arr[1]}'
}

function checkVersion() {
    [[ "$(remoteVersion)" == "$(installedVersion)" ]]
    return
}

function getDownloadLink() {
    echo "https://go.dev$(echo $links | awk -v arch="${arch}" '$0~arch {print $1}')"
}

function upgrade() {
    if checkVersion; then
        echo "Current version $(installedVersion) is the same as upstream. Not doing anything"
        return
    fi
    echo "current version is $(installedVersion). Downloading new version $(remoteVersion)."
    fpath=/usr/local
    sudo rm -r "${fpath}/go"
    curl -L $(getDownloadLink) 2>/dev/null | sudo tar -C $fpath -vxz
}

if [[ "${1}" == "install" ]]; then
    upgrade
else
    echo "Current version: $(installedVersion)\nRemote version:  $(remoteVersion)\nDownload link:   $(getDownloadLink)"
    checkVersion
fi