Skip to content

Instantly share code, notes, and snippets.

@JohnDDuncanIII
Last active March 21, 2024 01:50
Show Gist options
  • Save JohnDDuncanIII/4aff5394f5edad6a1817d7e433c4e56c to your computer and use it in GitHub Desktop.
Save JohnDDuncanIII/4aff5394f5edad6a1817d7e433c4e56c to your computer and use it in GitHub Desktop.
update_go() {
ARCH="$(uname -m | sed 's/^..86$$/386/; s/^.86$$/386/; s/x86_64/amd64/; s/arm.*/arm/; s/aarch64/arm64/')"
OS="$(uname | tr "[:upper:]" "[:lower:]" | sed 's/mingw/windows/; s/.*windows.*/windows/')"
# if the $GOROOT environment variable does not exist...
if [ -z "$GOROOT" ]
then
# if go is installed
if [ -x "$(command -v go)" ]
then
# get the GOROOT from the installed `go env` command
GOROOT=$(go env GOROOT)
else
# GOROOT=/usr/local/go
GOROOT=/opt/go
fi
fi
cd $GOROOT/.. || return
# go1.16.5
local GO_VERSION_REMOTE
GO_VERSION_REMOTE=$(curl "https://go.dev/VERSION?m=text" | head -n1)
# go version go1.16.5 darwin/arm64
# to
# go1.16.5
local GO_VERSION
GO_VERSION=$(go version | cut -d " " -f 3)
# if go is not installed or is installed and outdated
# https://stackoverflow.com/a/8811800/
# https://stackoverflow.com/a/2830416/
# [[ $(go version) != *$GO_VERSION_REMOTE* ]]
if [ ! -x "$(command -v go)" ] || [ "$GO_VERSION" != "$GO_VERSION_REMOTE" ]
then
# macOS
[ -d ~/.Trash ] && TRASHDIR=~/.Trash
# Linux, *BSD, Solaris, etc.
# https://askubuntu.com/a/102106
# https://unix.stackexchange.com/a/84330
# https://blogs.oracle.com/solaris/dealing-with-the-trash-v2
[ -d ~/.local/share/Trash ] && TRASHDIR=~/.local/share/Trash
# XDG Base Directory
# https://specifications.freedesktop.org/trash-spec/trashspec-1.0.html
# https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
[ -d "$XDG_DATA_HOME/Trash" ] && TRASHDIR=$XDG_DATA_HOME/Trash
if [ -d go/ ]
then
if [ -n "$TRASHDIR" ]
then
# move the old go install to the trash
sudo mv -fv go/ "$TRASHDIR"
else
# delete the old go install
rm -rf go/
fi
fi
echo $GO_VERSION_REMOTE
echo $OS
echo $ARCH
echo "https://dl.google.com/go/$GO_VERSION_REMOTE.$OS-$ARCH.tar.gz"
# install the latest version of go
sudo curl "https://dl.google.com/go/$GO_VERSION_REMOTE.$OS-$ARCH.tar.gz" | sudo tar -xzvf -
else
echo "Go $GO_VERSION_REMOTE already installed."
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment