Created
December 24, 2025 10:50
-
-
Save suchasplus/e11e165f75a17e7bcca3bd06b9083528 to your computer and use it in GitHub Desktop.
PATH 去重函数 - bash 4+ / zsh 兼容
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # PATH 去重函数 - bash 4+ / zsh 兼容 | |
| # 添加到 ~/.bashrc 或 ~/.zshrc | |
| # eg: | |
| # cpp > /dev/null | |
| # 去重 PATH,保留首次出现的条目 | |
| dedup_path() { | |
| local -A seen | |
| local new_path="" | |
| local dir | |
| while IFS= read -r dir; do | |
| [[ -z "$dir" ]] && continue | |
| if [[ -z "${seen[$dir]}" ]]; then | |
| seen[$dir]=1 | |
| new_path="${new_path:+$new_path:}$dir" | |
| fi | |
| done < <(echo "$PATH" | tr ':' '\n') | |
| export PATH="$new_path" | |
| echo "PATH 已去重: $(echo "$PATH" | tr ':' '\n' | wc -l | tr -d ' ') 条目" | |
| } | |
| # 重置 PATH 为系统默认值 | |
| reset_path() { | |
| if [[ "$(uname)" == "Darwin" ]]; then | |
| PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" | |
| [[ -d "/opt/homebrew/bin" ]] && PATH="/opt/homebrew/bin:/opt/homebrew/sbin:$PATH" | |
| else | |
| PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" | |
| fi | |
| local p | |
| for p in "$HOME/.local/bin" "$HOME/bin" "$HOME/.cargo/bin" "$HOME/go/bin"; do | |
| [[ -d "$p" ]] && PATH="$p:$PATH" | |
| done | |
| dedup_path | |
| } | |
| # 显示 PATH(带序号和存在性检查) | |
| show_path() { | |
| local i=1 dir | |
| while IFS= read -r dir; do | |
| [[ -z "$dir" ]] && continue | |
| if [[ -d "$dir" ]]; then | |
| printf "%2d. %s\n" $i "$dir" | |
| else | |
| printf "%2d. %s \e[31m[无效]\e[0m\n" $i "$dir" | |
| fi | |
| ((i++)) | |
| done < <(echo "$PATH" | tr ':' '\n') | |
| } | |
| # 清理 PATH:去重 + 移除无效目录 | |
| clean_path() { | |
| local -A seen | |
| local new_path="" | |
| local dir | |
| while IFS= read -r dir; do | |
| [[ -z "$dir" || ! -d "$dir" ]] && continue | |
| if [[ -z "${seen[$dir]}" ]]; then | |
| seen[$dir]=1 | |
| new_path="${new_path:+$new_path:}$dir" | |
| fi | |
| done < <(echo "$PATH" | tr ':' '\n') | |
| export PATH="$new_path" | |
| echo "PATH 已清理: $(echo "$PATH" | tr ':' '\n' | wc -l | tr -d ' ') 条目" | |
| } | |
| alias dp='dedup_path' | |
| alias sp='show_path' | |
| alias rp='reset_path' | |
| alias cpp='clean_path' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment