Skip to content

Instantly share code, notes, and snippets.

@eggbean
Last active September 13, 2024 17:04
Show Gist options
  • Save eggbean/7f977f61327500c3f291ed36078b457f to your computer and use it in GitHub Desktop.
Save eggbean/7f977f61327500c3f291ed36078b457f to your computer and use it in GitHub Desktop.
Script for automated installation or updating Go. For Linux and macOS, x86_64, arm64 and arm.
#!/bin/bash -e
# This script installs or updates to the latest version of Go.
# Multi-platform (Linux and macOS)
# Multi-architecture (amd64, arm64, arm) support
#
# Add to your .profile, .bash_profile or .zshenv:
# export PATH=$PATH:/usr/local/go/bin
error_string=("Error: This command has to be run with superuser"
"privileges (under the root user on most systems).")
if [[ $(id -u) -ne 0 ]]; then echo "${error_string[@]}" >&2; exit 1; fi
deps=( curl jq )
unset bail
for i in "${deps[@]}"; do command -v "$i" >/dev/null 2>&1 || { bail="$?"; echo "$i" is not available; }; done
if [ "$bail" ]; then exit "$bail"; fi
version="$(curl -s 'https://go.dev/dl/?mode=json' | jq -r '.[0].version')"
current="$(/usr/local/go/bin/go version 2>/dev/null | awk '{print $3}')"
if [[ "$current" == "$version" ]]; then
echo "Go is already up-to-date at version ${version}"
exit 0
fi
update_go() {
local arch="$1"
local os="$2"
local go_url="https://golang.org/dl/${version}.${os}-${arch}.tar.gz"
curl -so "/tmp/${version}.${os}-${arch}.tar.gz" -L "$go_url" && \
rm -rf /usr/local/go && tar -C /usr/local -xzf /tmp/${version}.${os}-${arch}.tar.gz
tar -C /usr/local -xzf "/tmp/${version}.${os}-${arch}.tar.gz" && \
echo "Go updated to version ${version}"
rm "/tmp/${version}.${os}-${arch}.tar.gz"
}
case "$(uname -s)" in
Linux)
case "$(uname -m)" in
armv6l|armv7l)
update_go "armv6l" "linux"
;;
arm64)
update_go "arm64" "linux"
;;
x86_64)
update_go "amd64" "linux"
;;
*)
echo "Unsupported architecture: $(uname -m)" >&2
exit 1
;;
esac
;;
Darwin)
case "$(uname -m)" in
arm64)
update_go "arm64" "darwin"
;;
x86_64)
update_go "amd64" "darwin"
;;
*)
echo "Unsupported architecture: $(uname -m)" >&2
exit 1
;;
esac
;;
*)
echo "Unsupported operating system: $(uname -s)" >&2
exit 1
;;
esac
/usr/local/go/bin/go version
@clement2026
Copy link

Download and run the script (in case I need to run it again later 😎):

curl -O https://gist.githubusercontent.com/eggbean/7f977f61327500c3f291ed36078b457f/raw/4d3681569658834cb3a6344ff69358db974a553e/install_golang.sh
chmod +x install_golang.sh
./install_golang.sh
rm ./install_golang.sh

@eggbean
Copy link
Author

eggbean commented Sep 13, 2024

@clement2026 That would be good to put in cloud instance bootstrap scripts to add golang to your instances.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment