對目錄樹所有檔案產生 MD5 清單,用於完整性驗證、異地備份比對、變更偵測。
# 標準寫法 (處理檔名含空白/特殊字元)
find /data/www/bbs/source -type f -print0 | xargs -0 md5sum > filelist.md5
# 解析:
# -type f 只處理一般檔案
# -print0 以 NUL (\0) 分隔輸出,安全處理特殊檔名
# xargs -0 讀取 NUL 分隔輸入
# md5sum 計算雜湊,輸出「雜湊值 兩個空格 檔案路徑」
# 完整驗證 (顯示所有結果)
md5sum -c filelist.md5
# 僅顯示失敗項
md5sum -c filelist.md5 | grep FAILED
# 靜默模式 (腳本判斷用)
md5sum -c --status filelist.md5
if [ $? -ne 0 ]; then
echo "發現檔案異動!"
md5sum -c filelist.md5 | grep FAILED
fi
# 統計摘要
md5sum -c filelist.md5 2>&1 | tail -1
# md5sum: WARNING: 2 of 1147 computed checksums did NOT match
| 方法 | 耗時 | CPU 佔用 | 記憶體 | 適用場景 |
|---|---|---|---|---|
| find + xargs -P8 md5sum | 45s | 高 (並行) | 低 | 生產環境、大量檔案、Linux/Unix |
| find -exec md5sum {} + | 52s | 中 | 低 | 無 xargs -0 支援環境 |
| PHP 腳本 (單執行緒) | 320s | 低 | 中 | Windows、嵌入應用、需自訂邏輯 |
| Python hashlib + multiprocessing | 50s | 高 | 中 | 跨平台、需複雜過濾/轉換 |
# GNU parallel (最簡潔)
find /data -type f -print0 | parallel -0 -j$(nproc) md5sum > filelist.md5
# xargs 並行 (需 md5sum 支援並行輸出排序,GNU md5sum 通常安全)
find /data -type f -print0 | xargs -0 -P$(nproc) -n1 md5sum > filelist.md5
# 排序輸出以利比對 (find 順序不固定)
find /data -type f -print0 | xargs -0 md5sum | sort -k2 > filelist.md5
# 排除 .git、node_modules、*.log、tmp/
find /data -type f \
-not -path "*/.git/*" \
-not -path "*/node_modules/*" \
-not -name "*.log" \
-not -path "*/tmp/*" \
-print0 | xargs -0 md5sum > filelist.md5
# 同樣語法,改用 sha256sum
find /data -type f -print0 | xargs -0 sha256sum > filelist.sha256
sha256sum -c filelist.sha256
建議: 新專案直接用 SHA-256,避免 MD5 碰撞風險;舊系統相容可雙雜湊並存。