Skip to content

Instantly share code, notes, and snippets.

@holly
Created March 21, 2022 18:16
Show Gist options
  • Save holly/12981ee941f76c6f223b738039868c79 to your computer and use it in GitHub Desktop.
Save holly/12981ee941f76c6f223b738039868c79 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -e
set -o pipefail
GO_VERSION=1.17.7
GO_PATH=/usr/local/bin/go
GOFMT_PATH=/usr/local/bin/gofmt
MODE=$1
if [ "$MODE" != "install" -a "$MODE" != "uninstall" -a "$MODE" != "switch" -a "$MODE" != "list" ]; then
echo "Usage: go_install.sh [install|uninstall|switch|list]"
exit 1
fi
install() {
if [ -n "$1" ]; then
GO_VERSION=$1
fi
DOWNLOAD_URL="https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz"
SAVE_DIR="/usr/local/go-${GO_VERSION}"
if [ -d $SAVE_DIR ]; then
echo "go $GO_VERSION is already installed."
exit 1
fi
curl -sL $DOWNLOAD_URL -o - | tar -C /usr/local -xzf -
mv /usr/local/go $SAVE_DIR
if [ $(go_list | wc -l) -eq 1 ]; then
switch $GO_VERSION
fi
}
switch() {
if [ -n "$1" ]; then
GO_VERSION=$1
fi
if [ $GO_VERSION = $(go_current) ]; then
echo "current go version is $GO_VERSION."
exit 1
fi
SAVE_DIR="/usr/local/go-${GO_VERSION}"
ln -sf $SAVE_DIR/bin/go /usr/local/bin/go
ln -sf $SAVE_DIR/bin/gofmt /usr/local/bin/gofmt
}
uninstall() {
if [ -n "$1" ]; then
GO_VERSION=$1
fi
SAVE_DIR="/usr/local/go-${GO_VERSION}"
if [ ! -d $SAVE_DIR ]; then
echo "go $GO_VERSION is not exists."
exit 1
fi
NUM=$(go_list | wc -l)
rm -frv $SAVE_DIR
if [ $NUM -eq 1 ]; then
rm -f /usr/local/bin/go /usr/local/bin/gofmt
else
switch $(go_list | head -1)
fi
}
list() {
current=$(go_current)
if [ $current = "none" ]; then
echo "go is not installed."
exit
fi
for go in $(go_list); do
if echo $go | grep -q $current; then
echo "$go (current)"
else
echo $go
fi
done
}
go_list() {
for d in $(ls -1dv /usr/local/go-* | sort -r); do
echo $d | sed -e 's|^/usr/local/go-||'
done
}
go_current() {
if [ -L $GO_PATH ]; then
realpath=$(readlink $GO_PATH)
if [ -x $realpath ]; then
$GO_PATH version | sed -e 's/^go version go\(.*\) .*$/\1/'
else
echo "none"
fi
else
echo "none"
fi
}
case "$MODE" in
"install" )
install $2;;
"uninstall" )
uninstall $2;;
"switch" )
switch $2;;
"list" )
list ;;
* ) break ;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment