set -o errexit
#set -o xtrace
VERSION="1.11"
print_help() {
echo "Usage: ./golang_install.sh [OPTIONS]"
echo -e "\nOptions::"
echo -e " -i|--install\tInstall Go matches current arch"
echo -e " -r|--remove\tTo remove currently installed version"
echo -e " -v|--version\tInstall specified version,default version 1.11"
echo -e " -h|--help\tDisplay this message"
echo -e "\nExample::"
echo -e " ./golang_install.sh\t\t#Install version 1.11"
echo -e " ./golang_install.sh -v XXX\t#Install specified version"
echo -e " ./golang_install.sh -r\t#Uninstall Go"
}
remove_golang() {
rm -rf "$HOME/.go/"
sed -i '/# GoLang/d' "$HOME/.${shell_profile}"
sed -i '/export GOROOT/d' "$HOME/.${shell_profile}"
sed -i '/:$GOROOT/d' "$HOME/.${shell_profile}"
sed -i '/export GOPATH/d' "$HOME/.${shell_profile}"
sed -i '/:$GOPATH/d' "$HOME/.${shell_profile}"
if [ -d "/usr/local/go" ]; then
echo "Please remove /usr/local/go !"
fi
}
if [ -n "`$SHELL -c 'echo $ZSH_VERSION'`" ]; then
# assume Zsh
shell_profile="zshrc"
elif [ -n "`$SHELL -c 'echo $BASH_VERSION'`" ]; then
# assume Bash
shell_profile="bashrc"
fi
if [ -n "$1" ]; then
case $1 in
-r|--remove )
remove_golang
echo "Go removed..."
exit 0
;;
-i|--install )
echo "Install Golang..."
;;
-v|--version )
shift
if [ -n "$1" ]; then
VERSION=$1
echo "Go version:$VERSION"
else
echo "Version is NULL!"
print_help
exit 0
fi
;;
-h|--help )
print_help
exit 0
;;
* )
echo "Invalid parameter: "$1
print_help
exit 1
esac
fi
if test "$(uname -m)" = "aarch64" ; then
ARCH="arm64";
DFILE="go$VERSION.linux-arm64.tar.gz"
else
ARCH="amd64";
DFILE="go$VERSION.linux-amd64.tar.gz"
fi
if [ -d "$HOME/.go" ] || [ -d "$HOME/go" ]; then
echo "The 'go' or '.go' directories already exist. Exiting."
exit 1
fi
echo "Downloading $DFILE ..."
wget https://storage.googleapis.com/golang/$DFILE -O /tmp/go.tar.gz
if [ $? -ne 0 ]; then
echo "Download failed! Exiting."
exit 1
fi
echo "Extracting File..."
tar -C "$HOME" -xzf /tmp/go.tar.gz
mv "$HOME/go" "$HOME/.go"
touch "$HOME/.${shell_profile}"
{
echo '# GoLang'
echo 'export GOROOT=$HOME/.go'
echo 'export PATH=$PATH:$GOROOT/bin'
echo 'export GOPATH=$HOME/go'
echo 'export PATH=$PATH:$GOPATH/bin'
} >> "$HOME/.${shell_profile}"
mkdir -p $HOME/go/{src,pkg,bin}
echo -e "\nGo $VERSION was installed.\nMake sure to relogin into your shell or run:"
echo -e "\n\tsource $HOME/.${shell_profile}\n\nto update your environment variables."
echo "Tip: Opening a new terminal window usually just works. :)"
rm -f /tmp/go.tar.gz