将下面脚本保存为 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