#!/usr/bin/env bash # ============================================================================= # Claude / Anthropic 清理脚本 —— 综合版(跨平台,自动探测系统) # ----------------------------------------------------------------------------- # 功能: # 1. 自动探测系统:macOS / Linux / Windows(Git Bash) / 其它 # 2. 备份(迁移到桌面 ~/Desktop/Claude-backup-<时间戳>/) # 3. 清理其余 Claude / Anthropic 相关文件 # 4. 排除:openclaw、桌面文件、Clash 代理配置(claude.yaml)、外接卷(/Volumes/*) # 5. 执行完毕后,将全部备份项清单写入 txt # 6. 结束后自动销毁脚本自身(stdin 执行时自动跳过) # # 用法: # 本地交互: ./cleanup-claude.sh # 跳过确认: ./cleanup-claude.sh --yes (或 CLEANUP_CONFIRM=yes) # 只探测不执行:./cleanup-claude.sh --detect (打印系统 + 将执行的命令) # 远程(SSH): ssh user@host 'bash -s -- --yes' < cleanup-claude.sh # ============================================================================= set -uo pipefail # ---- 颜色输出 --------------------------------------------------------------- if [ -t 1 ]; then C_RESET=$'\033[0m'; C_BOLD=$'\033[1m' C_GREEN=$'\033[32m'; C_YELLOW=$'\033[33m'; C_RED=$'\033[31m'; C_CYAN=$'\033[36m' else C_RESET=''; C_BOLD=''; C_GREEN=''; C_YELLOW=''; C_RED=''; C_CYAN='' fi # ---- 公共变量 --------------------------------------------------------------- TS="$(date '+%Y%m%d-%H%M%S')-$$" HOME_DIR="${HOME:?}" DESKTOP_DIR="$HOME_DIR/Desktop" BACKUP_DIR="$DESKTOP_DIR/Claude-backup-${TS}" MANIFEST_FILE="$HOME_DIR/claude-cleanup-backups-${TS}.txt" BACKUP_MANIFEST=() FAILURES=0 # ---- 参数解析(遍历所有参数;--detect 优先,--yes 仅跳过确认)------------------ ARG_DETECT=0; ARG_YES=0 for a in "$@"; do case "$a" in --detect) ARG_DETECT=1 ;; --yes) ARG_YES=1 ;; esac done # ---- 输出函数 --------------------------------------------------------------- log() { printf '%s\n' "$*"; } info() { printf ' %s- %s%s\n' "${C_GREEN}" "$*" "${C_RESET}"; } skip() { printf ' %s! %s%s\n' "${C_YELLOW}" "$*" "${C_RESET}"; } step() { printf '\n%s==> %s%s\n' "${C_CYAN}${C_BOLD}" "$*" "${C_RESET}"; } note_fail() { FAILURES=$((FAILURES + 1)); } # 把 Git Bash 的 Windows 路径转成 Unix。转换失败或结果是根目录时返回非零, # 避免拼出 /Claude 这类路径交给 rm。 to_unix_path() { local raw="$1" converted="" if command -v cygpath >/dev/null 2>&1; then converted="$(cygpath -u "$raw" 2>/dev/null)" || converted="" if [ -z "$converted" ] || [ "$converted" = "/" ]; then printf '%s\n' "无法把 Windows 路径转换成 Unix 路径,已中止: $raw" >&2 return 1 fi case "$converted" in /*) printf '%s\n' "$converted"; return 0 ;; esac printf '%s\n' "cygpath 结果不是绝对路径,已中止: $converted" >&2 return 1 fi case "$raw" in [A-Za-z]:*|*\\*) printf '%s\n' "路径是 Windows 格式,且当前环境没有 cygpath,已中止: $raw" >&2 return 1 ;; esac if [ -z "$raw" ] || [ "$raw" = "/" ]; then printf '%s\n' "Windows 数据目录无效,已中止。" >&2 return 1 fi printf '%s\n' "$raw" } # ---- 备份:迁移到桌面备份目录 --------------------------------------------------- # 点开头的名字改成 dot- 前缀,避免 Finder 把备份藏起来。 # 同一备份目录里 basename 冲突时追加 -2、-3。 backup_dir() { local src="$1" if [ -e "$src" ] || [ -L "$src" ]; then mkdir -p "$BACKUP_DIR" local base dst n base="$(basename -- "$src")" case "$base" in .*) base="dot-${base#.}" ;; esac dst="$BACKUP_DIR/$base" n=2 while [ -e "$dst" ] || [ -L "$dst" ]; do dst="$BACKUP_DIR/${base}-${n}" n=$((n + 1)) done if mv -- "$src" "$dst"; then info "已备份(迁移到桌面): $src -> $dst" BACKUP_MANIFEST+=("$src|$dst") else skip "备份失败,跳过: $src"; note_fail fi else skip "不存在,跳过: $src" fi } # ---- 清理:删除单个路径 ------------------------------------------------------- remove() { local p="$1" if [ -e "$p" ] || [ -L "$p" ]; then if rm -rf -- "$p"; then info "已清理: $p"; else skip "清理失败: $p"; note_fail; fi else skip "不存在,跳过: $p" fi } # ---- 清理:按 find 模式批量删除 ------------------------------------------------- # 始终跳过以下目录(不扫描、不删除): # node_modules —— 依赖库目录(含 @anthropic-ai 等 SDK) # hermes/harness/openclaw(含 . 前缀)—— 第三方 agents 目录 remove_find() { local desc="$1"; shift local root="$1"; shift local matched=0 while IFS= read -r p; do [ -n "$p" ] || continue matched=1 if rm -rf -- "$p"; then info "已清理: $p"; else skip "清理失败: $p"; note_fail; fi done < <(find "$root" \ \( -type d \( -name node_modules -o -name hermes -o -name .hermes \ -o -name harness -o -name .harness \ -o -name openclaw -o -name .openclaw \) -prune \) \ -o \( "$@" \) -print 2>/dev/null) if [ "$matched" -eq 0 ]; then skip "无匹配,跳过: $desc"; fi } # ---- 探测:只列出 find 匹配项(不删除),供 --detect 使用 ----------------------- list_find() { local desc="$1"; shift local root="$1"; shift local found=0 log " ${C_BOLD}▸ ${desc}${C_RESET}" while IFS= read -r p; do [ -n "$p" ] || continue log " ${C_GREEN}[存在]${C_RESET} $p" found=1 done < <(find "$root" \ \( -type d \( -name node_modules -o -name hermes -o -name .hermes \ -o -name harness -o -name .harness \ -o -name openclaw -o -name .openclaw \) -prune \) \ -o \( "$@" \) -print 2>/dev/null) if [ "$found" -eq 0 ]; then log " ${C_CYAN}(无)${C_RESET}"; fi } # Safari 只处理 Claude / Anthropic 域名,不删除整份 Cookie、历史或全部网站数据。 SAFARI_HOST_RE='claude\.ai|claude\.com|anthropic\.com|anthropic\.ai' safari_scan_roots() { printf '%s\n' \ "$HOME_DIR/Library/Safari" \ "$HOME_DIR/Library/Caches/com.apple.Safari" \ "$HOME_DIR/Library/WebKit/com.apple.Safari" \ "$HOME_DIR/Library/Containers/com.apple.Safari/Data/Library" } safari_cookie_files() { printf '%s\n' \ "$HOME_DIR/Library/Cookies/Cookies.binarycookies" \ "$HOME_DIR/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies" } safari_history_dbs() { printf '%s\n' \ "$HOME_DIR/Library/Safari/History.db" \ "$HOME_DIR/Library/Containers/com.apple.Safari/Data/Library/Safari/History.db" } # 目录名是哈希时,按 origin 文件内容判断是不是 Claude 站点。 clean_safari_origin_dirs() { local root="$1" f dir [ -d "$root" ] || return 0 while IFS= read -r f; do [ -n "$f" ] || continue grep -a -I -q -E -i "$SAFARI_HOST_RE" "$f" || continue dir="$(dirname -- "$f")" case "$dir" in */WebsiteData/*/*) remove "$dir" ;; esac done < <(find "$root" -type f \( -name origin -o -name Origin \) 2>/dev/null) } safari_auth_py() { python3 - "$@" << 'PY' import sqlite3, struct, sys SUFFIXES = ("claude.ai", "claude.com", "anthropic.com", "anthropic.ai") def host_match(text): t = text.lower().strip() if "://" in t: t = t.split("://", 1)[1] t = t.split("/", 1)[0].split("?", 1)[0].split("#", 1)[0].split(":", 1)[0].lstrip(".") return any(t == s or t.endswith("." + s) for s in SUFFIXES) def cstr(buf, off): if off < 0 or off >= len(buf): return None end = buf.find(b"\x00", off) if end <= off: return None try: s = buf[off:end].decode("utf-8") except UnicodeDecodeError: return None if not s or any(ord(ch) < 32 for ch in s): return None return s def record_matches(rec): found = [] limit = min(len(rec) - 3, 80) for pos in range(16, limit, 4): off = struct.unpack_from("I", data, 4)[0] if num_pages > 100000: raise ValueError("页数异常") header = 8 + 4 * num_pages if header > len(data): raise ValueError("文件头损坏") sizes = struct.unpack_from(">" + "I" * num_pages, data, 8) if num_pages else () off = header pages = [] for sz in sizes: if sz < 8 or off + sz > len(data): raise ValueError("页长度损坏") pages.append(data[off:off + sz]) off += sz return pages def split_page(page): if len(page) < 8: raise ValueError("页过短") header, count = struct.unpack_from(" 100000: raise ValueError("Cookie 数量异常") table_end = 8 + 4 * count if table_end > len(page): raise ValueError("Cookie 偏移表损坏") offsets = struct.unpack_from("<" + "I" * count, page, 8) if count else () recs = [] for off in offsets: if off + 4 > len(page): raise ValueError("Cookie 偏移越界") size = struct.unpack_from(" len(page): raise ValueError("Cookie 长度不正确") recs.append(page[off:off + size]) return recs def build_page(recs): offsets = [] pos = 8 + 4 * len(recs) body = b"" for rec in recs: offsets.append(pos) body += rec pos += len(rec) page = struct.pack("I", len(pages))) for page in pages: out += struct.pack(">I", len(page)) for page in pages: out += page total = sum(sum(page) for page in pages) & 0xFFFFFFFFFFFFFFFF out += struct.pack(">Q", total) return bytes(out) def filter_cookies(path): with open(path, "rb") as fh: data = fh.read() groups = [] removed = 0 for page in parse_pages(data): kept = [] for rec in split_page(page): if record_matches(rec): removed += 1 else: kept.append(rec) groups.append(kept) if removed: tmp = path + ".cleanup-tmp" with open(tmp, "wb") as fh: fh.write(build_file(groups)) os.replace(tmp, path) print(removed) def filter_history(path): hosts = SUFFIXES parts = [] for host in hosts: parts.append(f"url LIKE '%://{host}' OR url LIKE '%://{host}/%' OR url LIKE '%://{host}?%' OR url LIKE '%://{host}#%'") parts.append(f"url LIKE '%://%.{host}' OR url LIKE '%://%.{host}/%' OR url LIKE '%://%.{host}?%' OR url LIKE '%://%.{host}#%'") where = " OR ".join(parts) con = sqlite3.connect(path) try: tables = {row[0] for row in con.execute("SELECT name FROM sqlite_master WHERE type='table'")} if "history_items" not in tables: print(0) return before = con.execute(f"SELECT COUNT(*) FROM history_items WHERE {where}").fetchone()[0] if "history_visits" in tables: con.execute(f"DELETE FROM history_visits WHERE history_item IN (SELECT id FROM history_items WHERE {where})") con.execute(f"DELETE FROM history_items WHERE {where}") con.commit() print(before) finally: con.close() import os cmd, path = sys.argv[1], sys.argv[2] if cmd == "cookies": filter_cookies(path) elif cmd == "history": filter_history(path) else: raise SystemExit("unknown command") PY } filter_safari_store() { local kind="$1" file="$2" n err msg [ -f "$file" ] || return 0 if ! command -v python3 >/dev/null 2>&1; then skip "没有 python3,跳过 Safari ${kind}: $file"; note_fail; return 0 fi err="$(mktemp "${TMPDIR:-/tmp}/safari-cleanup.XXXXXX")" if n="$(safari_auth_py "$kind" "$file" 2>"$err")"; then if [ "${n:-0}" -gt 0 ]; then info "已清理 Safari ${kind} 中的 Claude 记录 ${n} 条: $file" else skip "Safari ${kind} 中无 Claude 记录: $file" fi else msg="$(head -n 1 "$err" 2>/dev/null | tr '\r' ' ')" skip "Safari ${kind} 无法安全改写,已保留原文件: $file${msg:+ ($msg)}"; note_fail fi rm -f "$err" } # 找出真正需要「完全磁盘访问权限」的应用。Cursor 里运行时不是「终端」。 macos_privacy_app() { local pid="$$" comm while [ -n "$pid" ] && [ "$pid" -gt 1 ]; do comm="$(ps -p "$pid" -o comm= 2>/dev/null)" || break case "$comm" in *.app/Contents/MacOS/*) comm="${comm%.app/*}.app" printf '%s\n' "${comm##*/}" return 0 ;; esac pid="$(ps -p "$pid" -o ppid= 2>/dev/null | tr -d ' ')" done printf '%s\n' "终端" } # 目录存在但不能列出或写入。返回 0 表示被拦截。 dir_denied() { local p="$1" [ -d "$p" ] || return 1 [ -r "$p" ] && [ -w "$p" ] && [ -x "$p" ] || return 0 ls -d "$p/." >/dev/null 2>&1 || return 0 return 1 } linux_browser_roots() { printf '%s\n' \ "$HOME_DIR/.config/google-chrome" \ "$HOME_DIR/.config/BraveSoftware/Brave-Browser" \ "$HOME_DIR/.config/microsoft-edge" \ "$HOME_DIR/.config/chromium" \ "$HOME_DIR/.config/vivaldi" \ "$HOME_DIR/.config/opera" } windows_browser_roots() { printf '%s\n' \ "${local_appdata:-}/Google/Chrome/User Data" \ "${local_appdata:-}/BraveSoftware/Brave-Browser/User Data" \ "${local_appdata:-}/Microsoft/Edge/User Data" \ "${local_appdata:-}/Chromium/User Data" \ "${local_appdata:-}/Vivaldi/User Data" \ "${roaming:-}/Opera Software/Opera Stable" } # 检查已存在的浏览器配置目录。设置 BROWSER_DENIED=1 表示至少有一个读不到或写不了。 check_browser_access() { BROWSER_DENIED=0 local p seen=0 roots case "$OS_ID" in linux) roots=linux_browser_roots ;; windows) roots=windows_browser_roots ;; *) return 0 ;; esac log "${C_BOLD}【权限检查】${C_RESET}" if [ "$(id -u)" -eq 0 ]; then if [ "$OS_ID" = "linux" ]; then log " ${C_YELLOW}当前以 root 运行。浏览器缓存在普通用户主目录,不需要 sudo。${C_RESET}" elif [ "$OS_ID" = "windows" ]; then log " ${C_YELLOW}当前以管理员运行。浏览器缓存在当前用户的 AppData,不需要管理员权限。${C_RESET}" fi fi while IFS= read -r p; do [ -n "$p" ] && [ -d "$p" ] || continue seen=1 if dir_denied "$p"; then BROWSER_DENIED=1 log " ${C_RED}[无权限]${C_RESET} $p" else log " ${C_GREEN}[可读写]${C_RESET} $p" fi done < <("$roots") if [ "$BROWSER_DENIED" -eq 1 ]; then if [ "$OS_ID" = "windows" ]; then log " ${C_YELLOW}这些目录当前用户不能读写。请用安装该浏览器的 Windows 用户打开 Git Bash,不要用管理员身份。${C_RESET}" else log " ${C_YELLOW}这些目录当前用户不能读写。请用该浏览器所属的用户直接运行,不要加 sudo。${C_RESET}" fi elif [ "$seen" -eq 1 ]; then log " ${C_GREEN}浏览器配置目录可读写。${C_RESET}" else log " ${C_CYAN}未发现浏览器配置目录。${C_RESET}" fi } # 检查 Safari Cookie / 历史是否被 macOS 隐私保护拦截。不需要 sudo。 # 设置 MACOS_FDA_BLOCKED=1 表示文件存在但当前进程读不到。 check_macos_privacy() { MACOS_FDA_BLOCKED=0 [ "$OS_ID" = "macos" ] || return 0 log "${C_BOLD}【权限检查】${C_RESET}" if [ "$(id -u)" -eq 0 ]; then log " ${C_YELLOW}当前以 root 运行。清理浏览器缓存不需要 sudo,root 也不能绕过「完全磁盘访问权限」。${C_RESET}" fi local p blocked=0 checked=0 while IFS= read -r p; do [ -f "$p" ] || continue checked=1 if ( : < "$p" ) 2>/dev/null; then log " ${C_GREEN}[可读]${C_RESET} $p" else blocked=1 log " ${C_RED}[无权限]${C_RESET} $p" fi done < <(safari_cookie_files; safari_history_dbs) if [ "$blocked" -eq 1 ]; then MACOS_FDA_BLOCKED=1 local app app="$(macos_privacy_app)" log " ${C_YELLOW}「${app}」没有「完全磁盘访问权限」,Safari 的 Cookie 和历史会被系统拦截。${C_RESET}" log " ${C_YELLOW}系统设置 → 隐私与安全性 → 完全磁盘访问权限 → 打开「${app}」。${C_RESET}" log " ${C_YELLOW}然后用 Command+Q 完全退出「${app}」再打开。只关窗口不会生效。不要加 sudo。${C_RESET}" log " ${C_YELLOW}钥匙串删除时如果弹出授权框,点「允许」即可。${C_RESET}" elif [ "$checked" -eq 1 ]; then log " ${C_GREEN}Safari 受保护文件可读。${C_RESET}" else log " ${C_CYAN}未发现 Safari Cookie / 历史文件。${C_RESET}" fi } claude_host_match() { local h="${1#.}" h="${h%%/*}" local s for s in claude.ai claude.com anthropic.com anthropic.ai; do [ "$h" = "$s" ] && return 0 case "$h" in *."$s") return 0 ;; esac done return 1 } list_claude_keychain() { [ "${CLEANUP_SKIP_KEYCHAIN:-}" = "1" ] && return 0 command -v security >/dev/null 2>&1 || return 0 local value found=0 log " ${C_BOLD}▸ 钥匙串中的 Claude / Anthropic${C_RESET}" if security find-generic-password -s "Claude Safe Storage" >/dev/null 2>&1; then log " ${C_GREEN}[存在]${C_RESET} 通用密码 Claude Safe Storage" found=1 fi while IFS= read -r value; do [ -n "$value" ] || continue claude_host_match "$value" || continue log " ${C_GREEN}[存在]${C_RESET} 互联网密码服务器 $value" found=1 done < <(security dump-keychain 2>/dev/null | sed -n 's/.*"srvr"="\([^"]*\)".*/\1/p' | sort -u) [ "$found" -eq 0 ] && log " ${C_CYAN}(无)${C_RESET}" } clean_claude_keychain() { [ "${CLEANUP_SKIP_KEYCHAIN:-}" = "1" ] && return 0 command -v security >/dev/null 2>&1 || return 0 local n=0 value while security find-generic-password -s "Claude Safe Storage" >/dev/null 2>&1; do if security delete-generic-password -s "Claude Safe Storage" >/dev/null 2>&1; then n=$((n + 1)) else skip "钥匙串删除失败: Claude Safe Storage"; note_fail; break fi [ "$n" -ge 30 ] && break done [ "$n" -gt 0 ] && info "已清理钥匙串项目: Claude Safe Storage ($n)" while IFS= read -r value; do [ -n "$value" ] || continue claude_host_match "$value" || continue n=0 while security find-internet-password -s "$value" >/dev/null 2>&1; do if security delete-internet-password -s "$value" >/dev/null 2>&1; then n=$((n + 1)) else skip "钥匙串删除失败: $value"; note_fail; break fi [ "$n" -ge 30 ] && break done [ "$n" -gt 0 ] && info "已清理钥匙串互联网密码: $value ($n)" done < <(security dump-keychain 2>/dev/null | sed -n 's/.*"srvr"="\([^"]*\)".*/\1/p' | sort -u) } # ---- 探测系统 --------------------------------------------------------------- OS_ID="unknown"; OS_NAME="未知系统" case "$(uname -s)" in Darwin) OS_ID="macos"; OS_NAME="macOS" ;; Linux) OS_ID="linux"; OS_NAME="Linux" ;; MINGW*|MSYS*|CYGWIN*) OS_ID="windows"; OS_NAME="Windows (Git Bash)" ;; esac # 可选:环境变量强制指定系统(测试/特殊环境用) if [ -n "${CLEANUP_OS:-}" ]; then case "$CLEANUP_OS" in macos|linux|windows) OS_ID="$CLEANUP_OS" ;; *) log "${C_RED}无效的 CLEANUP_OS 值: ${CLEANUP_OS}(应为 macos/linux/windows)${C_RESET}"; exit 1 ;; esac case "$OS_ID" in macos) OS_NAME="macOS";; linux) OS_NAME="Linux";; windows) OS_NAME="Windows";; esac fi # Linux 中文环境桌面目录可能是 ~/桌面 if [ "$OS_ID" = "linux" ] && command -v xdg-user-dir >/dev/null 2>&1; then _xd="$(xdg-user-dir DESKTOP 2>/dev/null || true)" if [ -n "${_xd:-}" ] && [ "$_xd" != "/" ]; then DESKTOP_DIR="$_xd" BACKUP_DIR="$DESKTOP_DIR/Claude-backup-${TS}" fi unset _xd fi # ---- 各系统路径清单(用于 --detect 打印 + 执行)------------------------------- BACKUP_PATHS=(); CLEAN_PATHS=() case "$OS_ID" in macos) BACKUP_PATHS=( "$HOME_DIR/Library/Application Support/Claude" "$HOME_DIR/.claude" "$HOME_DIR/.claude.json" "$HOME_DIR/.claude.json.backup" ) CLEAN_PATHS=( "/Applications/Claude.app" "$HOME_DIR/Applications/Claude Code URL Handler.app" "$HOME_DIR/Library/Application Support/Claude-3p" "$HOME_DIR/.local/share/claude" "$HOME_DIR/.local/state/claude" "$HOME_DIR/.cache/claude" "$HOME_DIR/.local/bin/claude" "$HOME_DIR/Library/Caches/com.anthropic.claudefordesktop.ShipIt" "$HOME_DIR/Library/Caches/com.anthropic.claudefordesktop" "$HOME_DIR/Library/Caches/claude-cli-nodejs" "$HOME_DIR/Library/Logs/Claude" "$HOME_DIR/Library/Logs/Claude-3p" "$HOME_DIR/Library/Services/Claude - codeHere.workflow" "$HOME_DIR/Library/Services/Claude - send.workflow" "$HOME_DIR/Library/Services/Claude - ask.workflow" "$HOME_DIR/Library/Preferences/com.anthropic.claudefordesktop.plist" "$HOME_DIR/Library/HTTPStorages/com.anthropic.claudefordesktop" "$HOME_DIR/Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev" "/usr/local/bin/claude" "/opt/homebrew/bin/claude" ) ;; linux) BACKUP_PATHS=( "$HOME_DIR/.config/Claude" "$HOME_DIR/.claude" "$HOME_DIR/.claude.json" "$HOME_DIR/.claude.json.backup" ) CLEAN_PATHS=( "$HOME_DIR/.config/Claude-3p" "$HOME_DIR/.cache/Claude" "$HOME_DIR/.cache/claude" "$HOME_DIR/.local/share/claude" "$HOME_DIR/.local/state/claude" "$HOME_DIR/.local/bin/claude" "$HOME_DIR/.config/Code/User/globalStorage/saoudrizwan.claude-dev" "/usr/local/bin/claude" "/opt/homebrew/bin/claude" ) ;; windows) # Git Bash 的 APPDATA/LOCALAPPDATA 是 Windows 风格路径,先转成 Unix。 # 转失败就退出,不能把空字符串拼成 /Claude。 local_appdata="${LOCALAPPDATA:-$HOME_DIR/AppData/Local}" roaming="${APPDATA:-$HOME_DIR/AppData/Roaming}" if [ -n "${LOCALAPPDATA:-}" ]; then local_appdata="$(to_unix_path "$LOCALAPPDATA")" || exit 1 fi if [ -n "${APPDATA:-}" ]; then roaming="$(to_unix_path "$APPDATA")" || exit 1 fi BACKUP_PATHS=( "$HOME_DIR/.claude" "$HOME_DIR/.claude.json" "$HOME_DIR/.claude.json.backup" "$roaming/Claude" "$local_appdata/Claude" "$local_appdata/AnthropicClaude" ) CLEAN_PATHS=( "$local_appdata/Claude-3p" "$local_appdata/Packages/Claude_pzs8sxrjxfjjc/LocalCache/Roaming/Claude" "$local_appdata/Packages/Claude_pzs8sxrjxfjjc/LocalCache/Local/Claude-3p" ) ;; esac # ============================================================================= log "${C_BOLD}${C_CYAN}Claude / Anthropic 清理脚本(综合版)${C_RESET}" log "时间戳: ${TS}" log "检测到系统: ${C_BOLD}${OS_NAME}${C_RESET}" log "" # ---- --detect:只读探测,列出实际存在的 claude/anthropic 文件(不删除)---------- if [ "$ARG_DETECT" -eq 1 ]; then if [ "$OS_ID" = "unknown" ]; then log "${C_RED}无法识别的系统,无法继续。${C_RESET}"; exit 1 fi log "${C_BOLD}${C_CYAN}== 只读探测模式:列出实际存在的文件(不删除任何东西)==${C_RESET}" log "" # 1. 备份目标(含大小) log "${C_BOLD}【备份目标】→ 将迁移到桌面 ${BACKUP_DIR}${C_RESET}" for p in "${BACKUP_PATHS[@]}"; do if [ -e "$p" ] || [ -L "$p" ]; then sz=$(du -sh "$p" 2>/dev/null | cut -f1) log " ${C_GREEN}[存在]${C_RESET} $p ${C_YELLOW}(${sz:-未知})${C_RESET}" else log " ${C_CYAN}[不存在]${C_RESET} $p" fi done # 2. 清理目标(固定路径) log "" log "${C_BOLD}【清理目标】(固定路径)${C_RESET}" for p in "${CLEAN_PATHS[@]}"; do if [ -e "$p" ] || [ -L "$p" ]; then log " ${C_GREEN}[存在]${C_RESET} $p" else log " ${C_CYAN}[不存在]${C_RESET} $p" fi done # 3. 动态扫描(find 匹配到的实际文件) log "" log "${C_BOLD}【动态扫描】(浏览器缓存 / 扩展 / 日志)${C_RESET}" if [ "$OS_ID" = "macos" ]; then list_find "Cursor 日志" "$HOME_DIR/Library/Application Support/Cursor/logs" -type d -name 'Anthropic.claude-code' list_find "VS Code 日志" "$HOME_DIR/Library/Application Support/Code/logs" -type d -name 'Anthropic.claude-code' list_find "ByHost ShipIt plist" "$HOME_DIR/Library/Preferences/ByHost" -maxdepth 1 -type f -name 'com.anthropic.claudefordesktop*' list_find "Cursor 扩展" "$HOME_DIR/.cursor/extensions" -maxdepth 1 -type d -name 'anthropic.claude-code-*' list_find "VS Code 扩展" "$HOME_DIR/.vscode/extensions" -maxdepth 1 -type d \( -name 'saoudrizwan.claude-dev-*' -o -name 'anthropic.claude-code-*' \) list_find "VS Code VSIX 缓存" "$HOME_DIR/Library/Application Support/Code/CachedExtensionVSIXs" -maxdepth 2 \( -name 'anthropic.claude-code-*' -o -name 'saoudrizwan.claude-dev-*' \) list_find "Cursor VSIX 缓存" "$HOME_DIR/Library/Application Support/Cursor/CachedExtensionVSIXs" -maxdepth 2 \( -name 'anthropic.claude-code-*' -o -name 'saoudrizwan.claude-dev-*' \) list_find "浏览器 NativeMessagingHosts" "$HOME_DIR/Library/Application Support" -type f -name 'com.anthropic.*.json' -path '*/NativeMessagingHosts/*' for br in "$HOME_DIR/Library/Application Support/Google/Chrome" \ "$HOME_DIR/Library/Application Support/BraveSoftware/Brave-Browser" \ "$HOME_DIR/Library/Application Support/Arc/User Data" \ "$HOME_DIR/Library/Application Support/Microsoft Edge" \ "$HOME_DIR/Library/Application Support/Chromium" \ "$HOME_DIR/Library/Application Support/Vivaldi" \ "$HOME_DIR/Library/Application Support/com.operasoftware.Opera"; do [ -d "$br" ] || continue list_find "浏览器扩展 $(basename -- "$br")" "$br" -maxdepth 5 -type d -name 'fcoeoabgfenejglbffodgkkbkcdhcgfn' list_find "浏览器扩展 IndexedDB $(basename -- "$br")" "$br" -maxdepth 4 -name 'chrome-extension_fcoeoabgfenejglbffodgkkbkcdhcgfn*' list_find "站点缓存 $(basename -- "$br")" "$br" -maxdepth 6 \( \( -iname '*claude*' ! -iname 'claude.md' \) -o -iname '*anthropic*' \) done list_find "sot 应用缓存" "$HOME_DIR/Library/Application Support/sot/Partitions" -maxdepth 6 \( \( -iname '*claude*' ! -iname 'claude.md' \) -o -iname '*anthropic*' \) check_macos_privacy if [ "$MACOS_FDA_BLOCKED" -eq 0 ]; then while IFS= read -r br; do [ -d "$br" ] || continue list_find "Safari 站点数据 $(basename -- "$br")" "$br" -maxdepth 8 \( \( -iname '*claude*' ! -iname 'claude.md' \) -o -iname '*anthropic*' \) done < <(safari_scan_roots) log " ${C_BOLD}▸ Safari Cookie / 历史(只列文件,按 Claude 域名过滤)${C_RESET}" found=0 while IFS= read -r p; do if [ -f "$p" ]; then log " ${C_GREEN}[存在]${C_RESET} $p"; found=1; fi done < <(safari_cookie_files; safari_history_dbs) [ "$found" -eq 0 ] && log " ${C_CYAN}(无)${C_RESET}" else log " ${C_YELLOW}已跳过 Safari 站点扫描,避免把权限拦截误报成「无匹配」。${C_RESET}" fi list_claude_keychain elif [ "$OS_ID" = "linux" ]; then list_find "VS Code/Cursor 扩展" "$HOME_DIR/.vscode/extensions" -maxdepth 1 -type d \( -name 'saoudrizwan.claude-dev-*' -o -name 'anthropic.claude-code-*' \) list_find "Cursor 扩展" "$HOME_DIR/.cursor/extensions" -maxdepth 1 -type d -name 'anthropic.claude-code-*' list_find "VS Code VSIX 缓存" "$HOME_DIR/.config/Code/CachedExtensionVSIXs" -maxdepth 2 \( -name 'anthropic.claude-code-*' -o -name 'saoudrizwan.claude-dev-*' \) list_find "Cursor VSIX 缓存" "$HOME_DIR/.config/Cursor/CachedExtensionVSIXs" -maxdepth 2 \( -name 'anthropic.claude-code-*' -o -name 'saoudrizwan.claude-dev-*' \) list_find "VS Code 日志" "$HOME_DIR/.config/Code/logs" -type d -name 'Anthropic.claude-code' list_find "VS Code Server(远程) 扩展" "$HOME_DIR/.vscode-server/extensions" -maxdepth 1 -type d \( -name 'saoudrizwan.claude-dev-*' -o -name 'anthropic.claude-code-*' \) list_find "Cursor Server(远程) 扩展" "$HOME_DIR/.cursor-server/extensions" -maxdepth 1 -type d -name 'anthropic.claude-code-*' list_find "Cursor 日志" "$HOME_DIR/.config/Cursor/logs" -type d -name 'Anthropic.claude-code' check_browser_access while IFS= read -r br; do [ -d "$br" ] || continue dir_denied "$br" && continue list_find "浏览器扩展 $(basename -- "$br")" "$br" -maxdepth 5 -type d -name 'fcoeoabgfenejglbffodgkkbkcdhcgfn' list_find "浏览器扩展 IndexedDB $(basename -- "$br")" "$br" -maxdepth 4 -name 'chrome-extension_fcoeoabgfenejglbffodgkkbkcdhcgfn*' list_find "站点缓存 $(basename -- "$br")" "$br" -maxdepth 6 \( \( -iname '*claude*' ! -iname 'claude.md' \) -o -iname '*anthropic*' \) done < <(linux_browser_roots) [ "$BROWSER_DENIED" -eq 1 ] && log " ${C_YELLOW}已跳过无权限的浏览器目录,避免误报成「无匹配」。${C_RESET}" elif [ "$OS_ID" = "windows" ]; then log " ${C_YELLOW}Windows 原生环境建议用 PowerShell。本脚本在 Git Bash 下清理这些路径。${C_RESET}" log " ${C_YELLOW}WSL 会被识别为 Linux,不会清理 /mnt/c 里的 Windows 数据。${C_RESET}" check_browser_access while IFS= read -r br; do [ -d "$br" ] || continue dir_denied "$br" && continue list_find "浏览器扩展 $(basename -- "$br")" "$br" -maxdepth 5 -type d -name 'fcoeoabgfenejglbffodgkkbkcdhcgfn' list_find "浏览器扩展 IndexedDB $(basename -- "$br")" "$br" -maxdepth 4 -name 'chrome-extension_fcoeoabgfenejglbffodgkkbkcdhcgfn*' list_find "站点缓存 $(basename -- "$br")" "$br" -maxdepth 6 \( \( -iname '*claude*' ! -iname 'claude.md' \) -o -iname '*anthropic*' \) done < <(windows_browser_roots) [ "$BROWSER_DENIED" -eq 1 ] && log " ${C_YELLOW}已跳过无权限的浏览器目录,避免误报成「无匹配」。${C_RESET}" fi if [ -d "$HOME_DIR/.nvm/versions/node" ]; then list_find "nvm 的 claude 命令" "$HOME_DIR/.nvm/versions/node" -maxdepth 3 -name 'claude' log " ${C_BOLD}▸ nvm 的 @anthropic-ai/claude-code${C_RESET}" found=0 for p in "$HOME_DIR"/.nvm/versions/node/*/lib/node_modules/@anthropic-ai/claude-code; do if [ -e "$p" ] || [ -L "$p" ]; then log " ${C_GREEN}[存在]${C_RESET} $p"; found=1; fi done [ "$found" -eq 0 ] && log " ${C_CYAN}(无)${C_RESET}" fi log " ${C_BOLD}▸ bun 的 claude 命令 / 全局包 / 缓存${C_RESET}" found=0 for p in \ "$HOME_DIR/.bun/bin/claude" \ "$HOME_DIR/.bun/install/global/node_modules/@anthropic-ai/claude-code" \ "$HOME_DIR/.bun/install/cache/@anthropic-ai" do if [ -e "$p" ] || [ -L "$p" ]; then log " ${C_GREEN}[存在]${C_RESET} $p"; found=1; fi done [ "$found" -eq 0 ] && log " ${C_CYAN}(无)${C_RESET}" log "" log "${C_CYAN}探测完成(未删除任何文件)。确认无误后,去掉 --detect 加 --yes 执行正式清理。${C_RESET}" exit 0 fi if [ "$OS_ID" = "unknown" ]; then log "${C_RED}无法识别的系统,已中止。${C_RESET}"; exit 1 fi # ---- 安全确认 --------------------------------------------------------------- if [ "$ARG_YES" -eq 1 ] || [ "${CLEANUP_CONFIRM:-}" = "yes" ]; then CONFIRM="yes"; log "已通过 --yes / 环境变量确认执行。" elif [ -t 0 ] && [ -t 1 ]; then printf '确认执行清理?(输入 yes 继续): ' read -r CONFIRM < /dev/tty else log "${C_RED}非交互环境且未指定 --yes,已中止(防止误删)。${C_RESET}" exit 1 fi if [ "$CONFIRM" != "yes" ]; then log "${C_RED}已取消。${C_RESET}"; exit 1; fi # ---- Windows 提示 ----------------------------------------------------------- if [ "$OS_ID" = "windows" ]; then log "${C_YELLOW}提示:Windows 原生环境建议用 PowerShell。本脚本在 Git Bash 下清理。WSL 会被识别为 Linux,不会处理 /mnt/c 里的 Windows 数据。${C_RESET}" log "" fi # ============================= 执行 ========================================== step "1/3 备份(迁移到桌面,保留数据)" for p in "${BACKUP_PATHS[@]}"; do backup_dir "$p"; done step "2/3 清理配置与数据" for p in "${CLEAN_PATHS[@]}"; do remove "$p"; done step "3/3 清理编辑器扩展 / 浏览器缓存 / 日志" if [ "$OS_ID" = "macos" ]; then # ---- 编辑器日志(Cursor + VS Code)---- remove_find "Cursor 日志中的 Anthropic.claude-code" \ "$HOME_DIR/Library/Application Support/Cursor/logs" -type d -name 'Anthropic.claude-code' remove_find "VS Code 日志中的 Anthropic.claude-code" \ "$HOME_DIR/Library/Application Support/Code/logs" -type d -name 'Anthropic.claude-code' # ByHost 下的 ShipIt 残留 plist remove_find "ByHost 的 ShipIt plist" "$HOME_DIR/Library/Preferences/ByHost" \ -maxdepth 1 -type f -name 'com.anthropic.claudefordesktop*' # ---- IDE 扩展与缓存 ---- remove_find "Cursor 的 claude-code 扩展" "$HOME_DIR/.cursor/extensions" -maxdepth 1 -type d -name 'anthropic.claude-code-*' remove_find "VS Code 的 claude-dev / claude-code 扩展" "$HOME_DIR/.vscode/extensions" -maxdepth 1 -type d \( -name 'saoudrizwan.claude-dev-*' -o -name 'anthropic.claude-code-*' \) remove_find "VS Code 扩展缓存 VSIX" "$HOME_DIR/Library/Application Support/Code/CachedExtensionVSIXs" \ -maxdepth 2 \( -name 'anthropic.claude-code-*' -o -name 'saoudrizwan.claude-dev-*' \) remove_find "Cursor 扩展缓存 VSIX" "$HOME_DIR/Library/Application Support/Cursor/CachedExtensionVSIXs" \ -maxdepth 2 \( -name 'anthropic.claude-code-*' -o -name 'saoudrizwan.claude-dev-*' \) # ---- 浏览器:全面清理站点缓存 + 扩展(覆盖所有 Chromium 系浏览器)---- log "${C_YELLOW}⚠ 若浏览器正在运行,站点缓存删除后可能被重建,建议先关闭浏览器。${C_RESET}" # 各浏览器 NativeMessagingHosts 桥接 remove_find "浏览器 NativeMessagingHosts 桥接" "$HOME_DIR/Library/Application Support" \ -type f -name 'com.anthropic.*.json' -path '*/NativeMessagingHosts/*' BROWSER_ROOTS=( "$HOME_DIR/Library/Application Support/Google/Chrome" "$HOME_DIR/Library/Application Support/BraveSoftware/Brave-Browser" "$HOME_DIR/Library/Application Support/Arc/User Data" "$HOME_DIR/Library/Application Support/Microsoft Edge" "$HOME_DIR/Library/Application Support/Chromium" "$HOME_DIR/Library/Application Support/Vivaldi" "$HOME_DIR/Library/Application Support/com.operasoftware.Opera" ) for br in "${BROWSER_ROOTS[@]}"; do [ -d "$br" ] || continue # 1) Claude 浏览器扩展本体 remove_find "浏览器 Claude 扩展: $(basename -- "$br")" "$br" \ -maxdepth 5 -type d -name 'fcoeoabgfenejglbffodgkkbkcdhcgfn' # 1b) 扩展的 IndexedDB(chrome-extension__0.*) remove_find "浏览器扩展 IndexedDB: $(basename -- "$br")" "$br" \ -maxdepth 4 -name 'chrome-extension_fcoeoabgfenejglbffodgkkbkcdhcgfn*' # 2) 文件名含 claude / anthropic 的站点目录(如 IndexedDB)。 # Cookies、History、全站共用的 Local Storage 文件名不含这两个词,不删。 remove_find "浏览器站点缓存(claude/anthropic): $(basename -- "$br")" "$br" \ -maxdepth 6 \( \( -iname '*claude*' ! -iname 'claude.md' \) -o -iname '*anthropic*' \) done # 第三方应用「sot」内置浏览器的 claude.ai 缓存 remove_find "sot 应用的 claude.ai 缓存" "$HOME_DIR/Library/Application Support/sot/Partitions" \ -maxdepth 6 \( \( -iname '*claude*' ! -iname 'claude.md' \) -o -iname '*anthropic*' \) check_macos_privacy if [ "$MACOS_FDA_BLOCKED" -eq 0 ]; then while IFS= read -r br; do [ -d "$br" ] || continue remove_find "Safari 站点数据: $(basename -- "$br")" "$br" \ -maxdepth 8 \( \( -iname '*claude*' ! -iname 'claude.md' \) -o -iname '*anthropic*' \) clean_safari_origin_dirs "$br" done < <(safari_scan_roots) while IFS= read -r p; do filter_safari_store cookies "$p" done < <(safari_cookie_files) while IFS= read -r p; do filter_safari_store history "$p" done < <(safari_history_dbs) else skip "Safari 的 Cookie、历史和站点数据未清理。" note_fail fi clean_claude_keychain elif [ "$OS_ID" = "linux" ]; then remove_find "VS Code 的 claude-dev/claude-code 扩展" "$HOME_DIR/.vscode/extensions" \ -maxdepth 1 -type d \( -name 'saoudrizwan.claude-dev-*' -o -name 'anthropic.claude-code-*' \) remove_find "Cursor 的 claude-code 扩展" "$HOME_DIR/.cursor/extensions" \ -maxdepth 1 -type d -name 'anthropic.claude-code-*' remove_find "VS Code 扩展缓存 VSIX" "$HOME_DIR/.config/Code/CachedExtensionVSIXs" \ -maxdepth 2 \( -name 'anthropic.claude-code-*' -o -name 'saoudrizwan.claude-dev-*' \) remove_find "Cursor 扩展缓存 VSIX" "$HOME_DIR/.config/Cursor/CachedExtensionVSIXs" \ -maxdepth 2 \( -name 'anthropic.claude-code-*' -o -name 'saoudrizwan.claude-dev-*' \) remove_find "VS Code 日志中的 Anthropic.claude-code" "$HOME_DIR/.config/Code/logs" -type d -name 'Anthropic.claude-code' remove_find "VS Code Server(远程) 扩展" "$HOME_DIR/.vscode-server/extensions" \ -maxdepth 1 -type d \( -name 'saoudrizwan.claude-dev-*' -o -name 'anthropic.claude-code-*' \) remove_find "Cursor Server(远程) 扩展" "$HOME_DIR/.cursor-server/extensions" \ -maxdepth 1 -type d -name 'anthropic.claude-code-*' remove_find "Cursor 日志中的 Anthropic.claude-code" "$HOME_DIR/.config/Cursor/logs" -type d -name 'Anthropic.claude-code' check_browser_access while IFS= read -r br; do [ -d "$br" ] || continue if dir_denied "$br"; then skip "浏览器目录无权限,已跳过: $br" continue fi remove_find "浏览器 Claude 扩展: $(basename -- "$br")" "$br" \ -maxdepth 5 -type d -name 'fcoeoabgfenejglbffodgkkbkcdhcgfn' remove_find "浏览器扩展 IndexedDB: $(basename -- "$br")" "$br" \ -maxdepth 4 -name 'chrome-extension_fcoeoabgfenejglbffodgkkbkcdhcgfn*' remove_find "浏览器站点缓存(claude/anthropic): $(basename -- "$br")" "$br" \ -maxdepth 6 \( \( -iname '*claude*' ! -iname 'claude.md' \) -o -iname '*anthropic*' \) done < <(linux_browser_roots) [ "$BROWSER_DENIED" -eq 1 ] && note_fail elif [ "$OS_ID" = "windows" ]; then log "${C_YELLOW}⚠ 若浏览器正在运行,站点缓存删除后可能被重建,建议先关闭浏览器。${C_RESET}" check_browser_access while IFS= read -r br; do [ -d "$br" ] || continue if dir_denied "$br"; then skip "浏览器目录无权限,已跳过: $br" continue fi remove_find "浏览器 Claude 扩展: $(basename -- "$br")" "$br" \ -maxdepth 5 -type d -name 'fcoeoabgfenejglbffodgkkbkcdhcgfn' remove_find "浏览器扩展 IndexedDB: $(basename -- "$br")" "$br" \ -maxdepth 4 -name 'chrome-extension_fcoeoabgfenejglbffodgkkbkcdhcgfn*' remove_find "浏览器站点缓存(claude/anthropic): $(basename -- "$br")" "$br" \ -maxdepth 6 \( \( -iname '*claude*' ! -iname 'claude.md' \) -o -iname '*anthropic*' \) done < <(windows_browser_roots) [ "$BROWSER_DENIED" -eq 1 ] && note_fail fi # ---- nvm / bun 安装的 Claude Code CLI(macOS / Linux / Git Bash 通用)---- # @anthropic-ai 在 node_modules 内,会被 remove_find 剪枝,这里按已知路径删除 CLI。 # 只删 claude-code 包,同目录下的 SDK 保留。包删空后去掉空的 @anthropic-ai 目录。 if [ -d "$HOME_DIR/.nvm/versions/node" ]; then for p in "$HOME_DIR"/.nvm/versions/node/*/bin/claude \ "$HOME_DIR"/.nvm/versions/node/*/lib/node_modules/@anthropic-ai/claude-code; do if [ -e "$p" ] || [ -L "$p" ]; then remove "$p"; fi done for p in "$HOME_DIR"/.nvm/versions/node/*/lib/node_modules/@anthropic-ai; do if [ -d "$p" ]; then rmdir "$p" 2>/dev/null && info "已清理空目录: $p"; fi done fi for p in \ "$HOME_DIR/.bun/bin/claude" \ "$HOME_DIR/.bun/install/global/node_modules/@anthropic-ai/claude-code" \ "$HOME_DIR/.bun/install/cache/@anthropic-ai" do if [ -e "$p" ] || [ -L "$p" ]; then remove "$p"; fi done for p in "$HOME_DIR/.bun/install/global/node_modules/@anthropic-ai"; do if [ -d "$p" ]; then rmdir "$p" 2>/dev/null && info "已清理空目录: $p"; fi done # ============================= 备份清单 ======================================= { echo "Claude / Anthropic 清理 —— 备份清单" echo "生成时间: ${TS}" echo "系统: ${OS_NAME}" echo "脚本: $0" echo "============================================================" echo "" echo "共备份 ${#BACKUP_MANIFEST[@]} 项:" echo "" if [ "${#BACKUP_MANIFEST[@]}" -eq 0 ]; then echo " (无)" else for entry in "${BACKUP_MANIFEST[@]}"; do echo " [原路径] ${entry%%|*}" echo " [备份到] ${entry#*|}" echo "" done fi } > "$MANIFEST_FILE" log "" if [ "${#BACKUP_MANIFEST[@]}" -gt 0 ]; then log "${C_BOLD}备份数据已迁移到桌面:${C_RESET}${BACKUP_DIR}" else log "${C_YELLOW}本次无任何可备份项(未创建备份目录)。${C_RESET}" fi log "${C_BOLD}备份清单已保存:${C_RESET}${MANIFEST_FILE}" log "" log "${C_BOLD}以下项目已按要求排除:${C_RESET}" info "openclaw: 全局包(含其内 @anthropic-ai,保留)" info "node_modules: 项目内的依赖库目录保留。nvm/bun 只删 claude 命令和 claude-code 包" info "第三方 agents 目录: hermes / harness / openclaw 等(不扫描、不删除)" info "通用文件: CLAUDE.md / claude.md(保留,不删除)" info "桌面文件: ~/Desktop 下的 claude 相关文件" info "Clash 代理: ~/.config/clash.meta/claude.yaml(非 Claude 程序)" if [ "$OS_ID" = "macos" ]; then info "外接卷: /Volumes/Apps、/Volumes/Media、/Volumes/Backup、/Volumes/Data 等" fi log "" log "${C_BOLD}当前可用磁盘空间:${C_RESET}" df -h "$HOME_DIR" | tail -1 # ============================= 自毁 ========================================== log "" log "${C_YELLOW}脚本即将自我销毁...${C_RESET}" if [ -f "$0" ] && [ "$(basename -- "$0")" != "bash" ]; then rm -f -- "$0" && log "${C_GREEN}脚本已删除自身: $0${C_RESET}" else skip "脚本通过 stdin 执行,磁盘上无副本,无需删除" fi # ---- 退出码:有失败则非零 ---- if [ "$FAILURES" -gt 0 ]; then log "${C_RED}⚠ 有 ${FAILURES} 处操作失败,退出码 1。${C_RESET}" exit 1 fi exit 0