Skip to content

Instantly share code, notes, and snippets.

@fluffy-kaiju
Created March 31, 2025 16:26
Show Gist options
  • Save fluffy-kaiju/cb553efb7c875034365f34ac9b10841b to your computer and use it in GitHub Desktop.
Save fluffy-kaiju/cb553efb7c875034365f34ac9b10841b to your computer and use it in GitHub Desktop.
#!/bin/bash
export install_dir="/usr/local/golang"
if [ -z $VERSION ]
then
VERSION=$(curl -Ls https://go.dev/dl/?mode=json | jq -r '.[0].version')
echo "No version specified, using latest version: $VERSION"
fi
if [ -d "$install_dir/$VERSION" ]
then
echo "Go version $VERSION already installed"
echo "Symlinks for Go binaries in $install_dir/bin/:"
ls -l $install_dir/bin/
exit 0
fi
OS="linux"
ARCH="amd64"
go_file_json=$(curl -Ls "https://go.dev/dl/?mode=json" \
| VERSION="$VERSION" ARCH="$ARCH" OS="$OS" \
jq '
.[0].files[]
| select(.version | test(env.VERSION))
| select(.os | test(env.OS))
| select(.arch | test(env.ARCH))')
go_file_name=$(echo $go_file_json | jq -r '.filename')
echo "Downloading Go version $VERSION for $OS/$ARCH from $go_file_name"
tmp_dir=$(mktemp -d /tmp/go_install.XXXXXX)
echo "Downloading $go_file_name to $tmp_dir"
curl -s -Lo "$tmp_dir/$go_file_name" "https://go.dev/dl/$go_file_name"
echo "Checking checksum for $go_file_name"
go_file_sha256=$(echo $go_file_json | jq -r '.sha256')
shasum_res=$(echo "$go_file_sha256 $tmp_dir/$go_file_name" | sha256sum --check --status)
if [ ! $shasum_res ]; then
echo "Checksum verified for $go_file_name"
else
echo "Checksum verification failed for $go_file_name"
exit 1
fi
echo "Extracting $go_file_name"
install_dir_version="$install_dir/$VERSION"
sudo mkdir -p -v "$install_dir_version"
sudo tar -C $install_dir/$VERSION -xzf "$tmp_dir/$go_file_name"
echo "Adding go path"
sudo mkdir -p -v $install_dir/bin
function set_go_bin_link() {
echo "Creating symlink for $(basename $1) to $install_dir/bin/$(basename $1)"
sudo ln -sf "$1" $install_dir/bin/$(basename $1)
}
export -f set_go_bin_link
find $install_dir/$VERSION/go/bin/ -type f -executable -exec bash -c "set_go_bin_link {}" \;
if [ -f ~/.bashrc ]; then
echo "export GOROOT=$install_dir/$VERSION/go" >> ~/.bashrc
echo "export GOPATH=$HOME/go" >> ~/.bashrc
echo "export PATH=\$PATH:$install_dir/bin" >> ~/.bashrc
fi
if [ -f ~/.zshrc ]; then
echo "export GOROOT=$install_dir/$VERSION/go" >> ~/.zshrc
echo "export GOPATH=$HOME/go" >> ~/.zshrc
echo "export PATH=\$PATH:$install_dir/bin" >> ~/.zshrc
fi
rm -rf "$tmp_dir"
echo "Go version $VERSION for $OS/$ARCH installed successfully"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment