act_conda_envs(){# 检测当前使用的 shellif[ -n "$ZSH_VERSION"];then# 使用 zsh 的读取方法read_input(){echo -n "Enter the number of the environment to activate (or press Ctrl+c to exit): "read choice
}elif[ -n "$BASH_VERSION"];then# 使用 bash 的读取方法read_input(){read -p "Enter the number of the environment to activate (or press Ctrl+c to exit): " choice
}elseecho"Unsupported shell. This script works with zsh and bash."return1fi# 1. 执行 conda deactivate 命令,直到退出 base 环境while[["$CONDA_DEFAULT_ENV"=="base"]];do
conda deactivate
done# 2. 列出 conda env list 的内容,并添加编号echo"Listing conda environments with numbers:"env_list=$(conda env list |grep -v '#'|awk'{print $1}'|grep -v '^$')i=1whileIFS=read -r env;doecho"($i). $env"((i++))done<<<"$env_list"# 3. 等待用户输入,并执行激活该虚拟环境的命令whiletrue;do
read_input
if[["$choice"=~ ^[0-9]+$ ]]&&(( choice >=1&& choice <= i-1));thenselected_env=$(echo"$env_list"|sed -n "${choice}p")echo"Activating environment: $selected_env"
conda activate "$selected_env"breakelseecho"Invalid input. Please enter a number between 1 and $(($i-1))."fidone}
修改后执行source .bashrc或source .zshrc
结果
(base) think@xsyDL-4090solo:~$ act_conda_envs
Listing conda environments with numbers:
(1). base
(2). aidoc
(3). codegeex
(4). cogvlm2
(5). mem0ai
(6). sensevoice
(7). vllm
Enter the number of the environment to activate (or press Ctrl+c to exit): 5
Activating environment: mem0ai
(mem0ai) think@xsyDL-4090solo:~$