Skip to content

Instantly share code, notes, and snippets.

@ecnepsnai
Last active July 24, 2023 05:54
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 ecnepsnai/fcd02f855e2e8dd3c807caadcf3a010b to your computer and use it in GitHub Desktop.
Save ecnepsnai/fcd02f855e2e8dd3c807caadcf3a010b to your computer and use it in GitHub Desktop.
Script to manage go versions easily
#!/bin/bash
set -e
VERSION=$(curl -sS "https://go.dev/dl/?mode=json" | jq -r '.[0].version' | sed 's/go//')
INSTALL_DIR="/usr/local/go"
if [[ ! -d ${INSTALL_DIR} ]]; then
echo "Install directory '${INSTALL_DIR}' does not exist, sudo required to create it..."
sudo mkdir -p ${INSTALL_DIR}
fi
OWNED_BY=$(ls -ld ${INSTALL_DIR} | awk 'NR==1 {print $3}')
if [[ ${OWNED_BY} != $(whoami) ]]; then
echo "Install directory not writable by current user, sudo required to change that..."
sudo chown $(id -un):$(id -gn) ${INSTALL_DIR}
fi
VERSION_DIR="${INSTALL_DIR}/${VERSION}"
if [[ -d ${VERSION_DIR} ]]; then
>&2 echo "${VERSION_DIR} already exists, don't know what to do with it."
exit 1
fi
UNAME=$(uname | tr '[:upper:]' '[:lower:]')
ARCH="amd64"
if [[ $(uname -m) == "aarch64" ]]; then
ARCH="arm64"
fi
DL_URL="https://dl.google.com/go/go${VERSION}.${UNAME}-${ARCH}.tar.gz"
if [[ -d /tmp/go ]]; then
>&2 echo "/tmp/go already exists, don't know what to do with it."
exit 1
fi
cd /tmp
curl -Ss ${DL_URL} | tar -xzf -
mv go ${VERSION_DIR}
rm -f ${INSTALL_DIR}/current
ln -s ${VERSION_DIR} ${INSTALL_DIR}/current
if [[ :$PATH: == *:"${INSTALL_DIR}/current/bin":* ]]; then
echo "go updated to: $(go version)"
else
echo "go ${VERSION} installed but is missing from your \$PATH"
echo "Add the following line to your \$PATH variable:"
echo " ${INSTALL_DIR}/current/bin"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment