#!/usr/bin/env bash # Base 环境保护脚本 - 禁止向 base 环境安装包 # 位置: $CONDA_PREFIX/etc/conda/activate.d/99-base-protection.sh # 兼容: Bash / Zsh
# --- ZSH 兼容性设置 --- if [ -n "$ZSH_VERSION" ]; then # ZSH 数组索引默认从 1 开始,设置为与 Bash 一致(从 0 开始) setopt KSH_ARRAYS 2>/dev/null fi
# --- 辅助函数:检测是否目标为 base 环境 --- _is_target_base() { local args=("$@") local i=0 local next_val="" while [ $i -lt ${#args[@]} ]; do case"${args[$i]}"in -n|--name) # 检查下一个参数是否为 base next_val="${args[$((i+1))]}" if [ "$next_val" = "base" ]; then return 0 fi i=$((i+1)) ;; -n=*|--name=*) # 处理 --name=base 格式 local val="${args[$i]#*=}" if [ "$val" = "base" ]; then return 0 fi ;; -p|--prefix) # 检查下一个参数是否为 base 路径 next_val="${args[$((i+1))]}" if [ "$next_val" = "$CONDA_PREFIX" ] || [ "$next_val" = "/home/cpu/miniforge3" ]; then return 0 fi i=$((i+1)) ;; -p=*|--prefix=*) local val="${args[$i]#*=}" if [ "$val" = "$CONDA_PREFIX" ] || [ "$val" = "/home/cpu/miniforge3" ]; then return 0 fi ;; esac i=$((i+1)) done return 1 }
# --- Conda 保护函数 --- conda_protector() { local cmd="$1" # 只拦截 install 命令 if [ "$cmd" = "install" ]; then # 情况1: 当前在 base 环境且没有指定 -n 其他环境 if [ "$CONDA_DEFAULT_ENV" = "base" ]; then # 检查是否指定了 -n 或 --name 到其他环境 local has_other_target=false local args=("$@") local i=0 local next_val="" while [ $i -lt ${#args[@]} ]; do case"${args[$i]}"in -n|--name) next_val="${args[$((i+1))]}" if [ "$next_val" != "base" ]; then has_other_target=true fi ;; -n=*|--name=*) local val="${args[$i]#*=}" if [ "$val" != "base" ]; then has_other_target=true fi ;; -p|--prefix) next_val="${args[$((i+1))]}" if [ "$next_val" != "$CONDA_PREFIX" ] && [ "$next_val" != "/home/cpu/miniforge3" ]; then has_other_target=true fi ;; -p=*|--prefix=*) local val="${args[$i]#*=}" if [ "$val" != "$CONDA_PREFIX" ] && [ "$val" != "/home/cpu/miniforge3" ]; then has_other_target=true fi ;; esac i=$((i+1)) done if [ "$has_other_target" = false ]; then echo echo"❌ 操作被阻止:禁止向 (base) 环境安装包。" echo"👉 请先激活目标环境,或使用 -n <环境名> 指定目标环境。" echo"✅ 示例: conda activate <环境名> && conda install <包名>" echo"✅ 或者: conda install -n <环境名> <包名>" echo return 1 fi fi # 情况2: 不在 base,但显式指定 -n base 或 --prefix 到 base if _is_target_base "$@"; then echo echo"❌ 操作被阻止:禁止向 (base) 环境安装包。" echo"👉 请使用其他环境名替代 'base'。" echo return 1 fi fi command conda "$@" }