將下面腳本保存為 campare.sh 文件,執(zhí)行
sh campare.sh 文件夾1 文件夾2
#!/bin/bash
# 檢查參數(shù)數(shù)量
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
# 找出所有的文件,并進行內(nèi)容比較
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