MD5 校验脚本
学习笔记:MD5 校验脚本
01. 代码一(针对符号链接处理)
#!/bin/bash
out="all_md5.txt"
> "$out"# 遍历当前目录下所有 D120_* 子目录
for dir in D120_*; doecho "📁 处理目录: $dir"# 遍历目录下的每个符号链接for link in "$dir"/*; doif [ -L "$link" ]; thentarget=$(readlink -f "$link")if [ -f "$target" ]; then# 计算 md5 并替换为相对路径输出md5=$(md5sum "$target" | awk '{print $1}')echo "$md5 ${link}" >> "$out"elif [ -d "$target" ]; then# 如果是目录,则递归计算其中所有文件的 MD5while IFS= read -r file; domd5=$(md5sum "$file" | awk '{print $1}')rel_path="${link}/$(basename "$file")"echo "$md5 $rel_path" >> "$out"done < <(find "$target" -type f)fifidoneecho "" >> "$out"
doneecho "✅ 所有目录的 MD5 已写入 $out"
02. 代码一解读
-
初始化输出文件
out="all_md5.txt" > "$out"- 定义输出文件,清空内容。
-
遍历目录
for dir in D120_*; do- 遍历当前目录下所有以
D120_开头的子目录。
- 遍历当前目录下所有以
-
遍历符号链接
for link in "$dir"/*; doif [ -L "$link" ]; then- 判断目录下的每个文件是否是 符号链接。
-
解析符号链接目标
target=$(readlink -f "$link")- 获取符号链接指向的真实路径(绝对路径)。
-
处理文件和目录
-
文件:
md5=$(md5sum "$target" | awk '{print $1}') echo "$md5 ${link}" >> "$out"- 计算 MD5,输出相对路径。
-
目录:
while IFS= read -r file; domd5=$(md5sum "$file" | awk '{print $1}')rel_path="${link}/$(basename "$file")"echo "$md5 $rel_path" >> "$out" done < <(find "$target" -type f)- 使用
find遍历目录下所有文件,计算 MD5,并输出相对路径。
- 使用
-
-
输出完成提示
echo "✅ 所有目录的 MD5 已写入 $out"
⚠️ 注意:
< <(...)是 Bash 的 process substitution,必须用 Bash 执行。
01. 代码二(直接递归所有目录)
#!/bin/bash
# 输出文件
out="md5_checksums.txt"
> "$out"# 遍历当前目录下所有子目录
for dir in */; doif [ -d "$dir" ]; thenecho "📁 正在处理目录: $dir"# 递归遍历目录下所有文件计算 MD5find "$dir" -type f -exec md5sum {} \; >> "$out"echo "" >> "$out"fi
doneecho "✅ 所有目录的 MD5 已写入 $out"
02. 代码二解读
-
初始化输出文件
- 与代码一相同,清空内容。
-
遍历目录
for dir in */; doif [ -d "$dir" ]; then- 遍历当前目录下所有子目录。
-
递归计算 MD5
find "$dir" -type f -exec md5sum {} \; >> "$out"find找到目录下所有文件。md5sum计算 MD5,并输出完整路径。
-
完成提示
- 同样打印提示信息,告诉用户 MD5 文件已经生成。
总结对比
| 特性 | 代码一 | 代码二 |
|---|---|---|
| 处理对象 | 针对符号链接(文件或目录) | 普通目录下所有文件 |
| 输出路径 | 相对路径(保持符号链接结构) | 默认 find 输出绝对或相对路径 |
| 复杂度 | 高,处理目录和文件两种情况 | 简单,直接递归 |
| 依赖 | Bash 执行(process substitution) | 可用 sh 或 bash |
学习重点:
- 符号链接的 MD5 计算需要区分链接指向文件或目录。
- 相对路径 vs 绝对路径输出对后续校验和比较很重要。
find ... -exec是快速处理目录文件的好方法。
