Mac上快速比较两个文件夹差异

将下面脚本保存为 campare.sh 文件,执行

sh campare.sh 文件夹1 文件夹2
#!/bin/bash

# 检查参数数量
if [ "$#" -ne 2 ]; then
    echo "Usage: $0 <dir1> <dir2>"
    exit 1
fi

dir1="$1"
dir2="$2"

# 确保目录存在
if [ ! -d "$dir1" ] || [ ! -d "$dir2" ]; then
    echo "Both arguments must be directories."
    exit 1
fi

# 找出所有的文件,并进行内容比较
find "$dir1" -type f | while read -r file1; do
    # 获取相对路径
    rel_path="${file1#$dir1/}"
    file2="$dir2/$rel_path"
    
    # 检查文件是否存在
    if [ -f "$file2" ]; then
        # 先比较文件大小
        size1=$(stat -f%z "$file1")
        size2=$(stat -f%z "$file2")
        
        if [ "$size1" -ne "$size2" ]; then
            echo "Different (size mismatch): $rel_path"
        else
            # 使用 shasum 进行哈希比较
            hash1=$(shasum -a 256 "$file1" | awk '{print $1}')
            hash2=$(shasum -a 256 "$file2" | awk '{print $1}')
            if [ "$hash1" != "$hash2" ]; then
                echo "Different (content mismatch): $rel_path"
            fi
        fi
    else
        echo "Missing in dir2: $rel_path"
    fi
done

# 处理 dir2 中存在但 dir1 中不存在的文件
find "$dir2" -type f | while read -r file2; do
    rel_path="${file2#$dir2/}"
    file1="$dir1/$rel_path"
    
    if [ ! -f "$file1" ]; then
        echo "Missing in dir1: $rel_path"
    fi
done
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容