Skip to content

Instantly share code, notes, and snippets.

@inhere
Created October 11, 2024 08:10
Show Gist options
  • Save inhere/7486a72d962e5333c305ab2d071590d4 to your computer and use it in GitHub Desktop.
Save inhere/7486a72d962e5333c305ab2d071590d4 to your computer and use it in GitHub Desktop.
简单方便的实现go,node等本机sdk的多版本管理。Simple and easy to realize go, node and other local sdk multi-version management.
#!/usr/bin/env bash
# backup the PATH
pathBak="$PATH"
# echo "$BASH_VERSION"
# 声明关联数组(bash > 4.2 版本)
declare -A env_paths=(
[node20]="/c/Users/inhere/workspace/env/node-sdk/node-v20.16.0-win-x64"
[node16]="/c/Users/inhere/workspace/env/node-sdk/node-v16.16.0-win-x64"
[node12]="/c/Users/inhere/workspace/env/node-sdk/node-v12.18.3-win-x64"
[php8.1]="/c/Users/inhere/workspace/env/php-sdk/php-8.1.10-win32-vs16-x64"
[go1.19]="/c/Users/inhere/workspace/env/go-sdk/go1.19.13/bin"
[go1.21]="/c/Users/inhere/workspace/env/go-sdk/go1.21.13/bin"
[go1.22]="/c/Users/inhere/workspace/env/go-sdk/go1.22.8/bin"
[go1.23]="/c/Users/inhere/workspace/env/go-sdk/go1.23.2/bin"
)
# 定义 useenv 函数
# useenv [node20|node16|node12|php8.1|go1.19|go1.21|go1.22|go1.23]
useenv() {
if [ $# -eq 0 ]; then
echo "Custom set used sdk env for current shell"
echo ""
echo "Usage: useenv [NAME]"
echo " NAME Want used env name. "
echo " allow: node20, node16, node12, php8.1, go1.19, go1.21, go1.22, go1.23"
echo ""
echo "Example:"
echo " useenv go1.19"
echo " useenv node16 go1.19 # apply multi at once"
return 0
fi
# 初始化新的 PATH
new_path=""
# 遍历所有传入的参数
for name in "$@"; do
echo "Will use env $name"
# 从关联数组中获取路径
if [[ -n "${env_paths[$name]}" ]]; then
new_path="${env_paths[$name]}:$new_path"
else
echo " WARNING: unknown env: $name"
fi
done
# 判断 new_path 是否为空
if [ -z "$new_path" ]; then
echo "ERROR: no valid env name provided"
return 1
fi
# 设置新的 PATH
export PATH="$new_path:$pathBak"
echo "Completed"
}
@inhere
Copy link
Author

inhere commented Oct 11, 2024

Usage

Show usage

$ useenv
Custom set used sdk env for current shell

Usage: useenv [NAME]
  NAME    Want used env name.
          allow: node20, node16, node12, php8.1, go1.19, go1.21, go1.22, go1.23

Example:
  useenv go1.19
  useenv node16 go1.19 # apply multi at once

Example

inhere@inhere-win MINGW64 ~/workspace
$ node -v
v12.18.3

inhere@inhere-win MINGW64 ~/workspace
$ useenv node16
Will use env node16
Completed

inhere@inhere-win MINGW64 ~/workspace
$ node -v
v16.16.0

Change multi sdk env at once:

$ useenv node20 go1.21
Will use env node20
Will use env go1.21
Completed

inhere@inhere-win MINGW64 ~/workspace
$ node -v; go version
v20.16.0
go version go1.21.13 windows/amd64

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment