Shell 函数实现Go语言多版本管理轻量级方案

现有的工具方案

  • https://github.com/moovweb/gvm
  • https://github.com/voidint/g

我的方案

优点:

  • 原生:基于 go 语言本身支持多版本的能力实现,可以下载任何官方发布的版本
  • 简单:shell 函数实现,直接集成到 bashrc 或 zshrc 中即可使用,无需额外配置
  • 可定制化:代码简单可根据自身需求定制

代码实现

gist地址:https://gist.github.com/vimiix/0927fdfbea926e869a2c631db9eeae8b

####### GOLANG VERSION MANAGE FUNCTIONS ######
# ref: https://go.dev/doc/manage-install
function goinstall() {echo "Downloading go$1 ..."go install golang.org/dl/go$1@latest && go$1 download
}function gouse() {gopath=$(go env GOPATH)if test -x ${gopath}/bin/go$1; thenrm -f ${gopath}/bin/goecho "Relink go with go$1 ..."ln -s ${gopath}/bin/go$1 ${gopath}/bin/goecho "Done"elseecho "Version $1 not installed"fi
}function golist() {current=$(go version | awk '{print $3}' | cut -c3-)for v in $(ls $(go env GOPATH)/bin | grep -E 'go(\d.*)' | cut -c3-);doif [ $v = $current ]; thenecho "$v (⇦ current)"elseecho $vfidone
}function gouninstall() {current=$(go version | awk '{print $3}' | cut -c3-)if [ $1 = $current ]; thenecho "version $1 is actived, please change to another version first"returnfiecho "Removing binary..."rm -f $(go env GOPATH)/bin/go$1echo "Removing sdk ..."rm -r ~/sdk/go$1echo "Done"
}

使用方式

  1. 将上面的代码粘贴到 ~/.bashrc (如果是zsh,则是 ~/.zshrc) 末尾,保存退出
  2. source ~/.bashrc 激活即可

使用演示

本文链接:https://my.lmcjl.com/post/12856.html

展开阅读全文

4 评论

留下您的评论.