golang•1.91 kB
#!/usr/bin/env bash
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
# Libraries usually need to support a sliding window of versions of Go. See
# https://go.dev/dl/ for the list of available versions.
#set -x # To enable tracing.
set -euo pipefail
# Check if a Go version is provided as the first argument
if [ -z "$1" ]; then
echo "Usage: $0 <go_version> <command> [arguments...]"
exit 1
fi
go_version="$1"
shift
# Construct the go tool name (e.g., go1.18, go1.20)
go_tool="go${go_version}"
# Check if the specified Go version is already installed. If not, install it.
if ! command -v "$go_tool" &>/dev/null; then
echo "Installing Go version $go_version..."
GOBIN="$HOME/go/bin" # or wherever you want your go binaries
export GOBIN
GOPATH="$HOME/go" # or wherever your go path is set
export GOPATH
go install "golang.org/dl/${go_tool}@latest"
if [ $? -ne 0 ]; then
echo "Failed to install Go version $go_version"
exit 1
fi
"$go_tool" download
# Add GOBIN to your PATH if it's not already there. This is crucial.
if [[ ":$PATH:" != *":$GOBIN:"* ]]; then
export PATH="$GOBIN:$PATH"
echo "Added $GOBIN to PATH. You may need to source your profile for this to take effect in future sessions."
fi
fi
# Execute the command with the specified Go version
"$HOME/go/bin/$go_tool" "$@"
exit $?