博罗县万年长

使用脚本实现自动清除指定文件夹下丢失链接文件的符号链接

2026-04-01 14:40:02 浏览次数:0
详细信息

Linux/Mac 系统脚本

1. Bash 脚本版本

#!/bin/bash

# 清理指定目录中的损坏符号链接
# 用法: ./clean_links.sh [目录路径]

TARGET_DIR="${1:-.}"

echo "正在扫描目录: $TARGET_DIR"

# 方法1: 使用 find 命令
find "$TARGET_DIR" -type l ! -exec test -e {} \; -print

# 询问是否删除
read -p "是否要删除这些损坏的符号链接? (y/n): " -n 1 -r
echo

if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "正在删除损坏的符号链接..."
    find "$TARGET_DIR" -type l ! -exec test -e {} \; -exec rm {} \;
    echo "操作完成!"
else
    echo "操作已取消。"
fi

2. 更安全的脚本版本(带确认)

#!/bin/bash

# 清理指定目录中的损坏符号链接(带详细输出)

TARGET_DIR="${1:-.}"

if [[ ! -d "$TARGET_DIR" ]]; then
    echo "错误: 目录不存在: $TARGET_DIR"
    exit 1
fi

echo "=== 扫描损坏的符号链接 ==="
echo "目标目录: $TARGET_DIR"
echo ""

# 查找损坏的链接
broken_links=()
while IFS= read -r -d $'\0' link; do
    if [[ ! -e "$link" ]]; then
        broken_links+=("$link")
    fi
done < <(find "$TARGET_DIR" -type l -print0)

if [[ ${#broken_links[@]} -eq 0 ]]; then
    echo "未找到损坏的符号链接。"
    exit 0
fi

echo "找到 ${#broken_links[@]} 个损坏的符号链接:"
echo "----------------------------------------"

for link in "${broken_links[@]}"; do
    target=$(readlink "$link")
    echo "• $link -> $target"
done

echo "----------------------------------------"

# 确认删除
read -p "是否删除这些损坏的链接? (yes/no): " answer
if [[ "$answer" != "yes" ]]; then
    echo "操作已取消。"
    exit 0
fi

# 删除损坏的链接
for link in "${broken_links[@]}"; do
    rm -v "$link"
done

echo "操作完成!已删除 ${#broken_links[@]} 个损坏的符号链接。"

Windows 系统脚本

3. PowerShell 脚本版本

# 清理损坏的符号链接
# 用法: .\Clean-BrokenLinks.ps1 [目录路径]

param(
    [string]$TargetPath = "."
)

Write-Host "正在扫描目录: $TargetPath" -ForegroundColor Cyan

# 获取所有符号链接
$brokenLinks = Get-ChildItem -Path $TargetPath -Recurse | Where-Object {
    $_.LinkType -ne $null -and !(Test-Path $_.FullName)
}

if ($brokenLinks.Count -eq 0) {
    Write-Host "未找到损坏的符号链接。" -ForegroundColor Green
    exit
}

Write-Host "找到 $($brokenLinks.Count) 个损坏的符号链接:" -ForegroundColor Yellow
Write-Host "----------------------------------------" -ForegroundColor Gray

foreach ($link in $brokenLinks) {
    Write-Host "• $($link.FullName)" -ForegroundColor Red
    if ($link.LinkType -eq "SymbolicLink") {
        $target = Get-Item $link.FullName | Select-Object -ExpandProperty Target
        Write-Host "  -> $target" -ForegroundColor DarkGray
    }
}

Write-Host "----------------------------------------" -ForegroundColor Gray

# 确认删除
$confirmation = Read-Host "是否删除这些损坏的链接? (y/n)"
if ($confirmation -eq 'y') {
    foreach ($link in $brokenLinks) {
        Remove-Item $link.FullName -Force -Verbose
    }
    Write-Host "操作完成!" -ForegroundColor Green
} else {
    Write-Host "操作已取消。" -ForegroundColor Yellow
}

4. Windows Batch 脚本版本

@echo off
setlocal enabledelayedexpansion

REM 清理损坏的符号链接
REM 用法: clean_links.bat [目录路径]

set "TARGET_DIR=%~1"
if "%TARGET_DIR%"=="" set "TARGET_DIR=."

echo 正在扫描目录: %TARGET_DIR%

REM 临时文件存储找到的链接
set TEMP_FILE=%TEMP%\broken_links.txt

REM 查找损坏的链接
dir "%TARGET_DIR%" /s /a:l /b > "%TEMP_FILE%" 2>nul
if errorlevel 1 (
    echo 无法访问目录: %TARGET_DIR%
    goto :end
)

set count=0
echo 损坏的符号链接:
echo ----------------------------------------

for /f "usebackq delims=" %%f in ("%TEMP_FILE%") do (
    dir "%%f" >nul 2>nul
    if errorlevel 1 (
        set /a count+=1
        echo !count!. %%f
        set "link[!count!]=%%f"
    )
)

echo ----------------------------------------
echo 共找到 %count% 个损坏的符号链接。

if %count% equ 0 (
    echo 未找到损坏的符号链接。
    goto :end
)

set /p confirm="是否删除这些损坏的链接? (y/n): "
if /i "!confirm!" neq "y" (
    echo 操作已取消。
    goto :end
)

echo 正在删除...
for /l %%i in (1,1,%count%) do (
    del "!link[%%i]!"
    echo 已删除: !link[%%i]!
)

echo 操作完成!

:end
del "%TEMP_FILE%" 2>nul
pause

Python 跨平台脚本

5. Python 脚本版本(推荐)

#!/usr/bin/env python3
"""
清理损坏的符号链接
支持跨平台:Linux, macOS, Windows
"""

import os
import sys
import platform

def find_broken_links(target_dir):
    """查找损坏的符号链接"""
    broken_links = []

    for root, dirs, files in os.walk(target_dir):
        # 处理文件
        for item in files + dirs:
            path = os.path.join(root, item)

            # 检查是否是符号链接且已损坏
            if os.path.islink(path):
                target = os.readlink(path)
                target_path = os.path.join(root, target) if not os.path.isabs(target) else target

                if not os.path.exists(target_path):
                    broken_links.append((path, target))

    return broken_links

def main():
    # 获取目标目录
    if len(sys.argv) > 1:
        target_dir = sys.argv[1]
    else:
        target_dir = input("请输入要扫描的目录路径(默认当前目录): ").strip()
        if not target_dir:
            target_dir = "."

    # 验证目录存在
    if not os.path.isdir(target_dir):
        print(f"错误: 目录不存在: {target_dir}")
        return 1

    print(f"正在扫描目录: {os.path.abspath(target_dir)}")
    print("=" * 50)

    # 查找损坏的链接
    broken_links = find_broken_links(target_dir)

    if not broken_links:
        print("未找到损坏的符号链接。")
        return 0

    print(f"找到 {len(broken_links)} 个损坏的符号链接:")
    print("-" * 50)

    for i, (link, target) in enumerate(broken_links, 1):
        print(f"{i:3d}. {link}")
        print(f"     -> {target}")

    print("-" * 50)

    # 确认删除
    response = input(f"\n是否删除这 {len(broken_links)} 个损坏的链接? (yes/no): ").strip().lower()

    if response != "yes":
        print("操作已取消。")
        return 0

    # 删除损坏的链接
    deleted_count = 0
    for link, target in broken_links:
        try:
            os.unlink(link)
            print(f"已删除: {link}")
            deleted_count += 1
        except Exception as e:
            print(f"删除失败 {link}: {e}")

    print(f"\n操作完成!成功删除 {deleted_count} 个损坏的符号链接。")
    return 0

if __name__ == "__main__":
    sys.exit(main())

使用说明

对于 Linux/Mac:

将脚本保存为 clean_links.sh 添加执行权限:chmod +x clean_links.sh 运行:./clean_links.sh /path/to/directory

对于 Windows:

将脚本保存为 .ps1.bat 文件 以管理员权限运行(如果需要) 在 PowerShell 中运行:.\clean_links.ps1 "C:\path\to\directory"

对于 Python 脚本:

确保已安装 Python 3.x 运行:python clean_links.py /path/to/directory

安全提示

先预览再删除:脚本会先显示找到的损坏链接,确认后再删除 备份重要数据:建议在操作前备份重要数据 测试环境:先在测试目录中运行脚本验证效果 权限要求:可能需要相应权限才能删除某些符号链接

这些脚本会安全地找出并清理指定目录中的损坏符号链接,避免手动查找的繁琐。

相关推荐