功能说明
脚本从 /etc、/var/log、/tmp 和当前目录出发,演示 find 的常见筛选方式:名称通配、大小阈值、修改时间、权限位、空目录以及多条件组合;同时展示 -exec、-printf 和 -print0 | xargs -0 三种后续处理方式,适合日志清理、配置盘点和批量统计。
关键代码
find /etc -maxdepth 2 -name "*.conf" -type f限制搜索深度并按名称与类型过滤,2>/dev/null屏蔽权限不足的报错。-size +1M表示大于 1MB,-mtime -1表示一天内修改,-mtime +30表示超过 30 天,-perm -o+w查找其他用户可写的文件。-exec wc -l {} +把多个文件批量传给命令,比每个文件执行一次更高效。\( -name "*.js" -o -name "*.ts" \)用括号和-o组合条件,括号需转义。-printf "%f\t%k KB\t%TY-%Tm-%Td\n"自定义输出文件名、占用块数和日期。-print0与xargs -0 -P4以空字符分隔路径,避免文件名中的空格被拆分,并开启 4 路并行。
使用注意
-printf、-perm 等选项在 GNU find 上可用,BSD/macOS 的 find 支持范围不同。搜索系统目录时建议加 -maxdepth 并重定向错误,避免遍历过深。用 -exec 处理用户可控路径时要防止命令注入,优先使用 {} + 传参而非拼接字符串。删除类操作建议先用 -print 确认结果。
验证方式
逐段执行各命令,确认配置文件、超大日志、近期修改文件、空目录和世界可写文件的输出符合预期。可用 find . -name "*.conf" | wc -l 与脚本输出对照,并在含空格的测试文件名下验证 -print0 管道不会拆行。
代码示例
#!/usr/bin/env bash
set -euo pipefail
# Find by name pattern
find /etc -maxdepth 2 -name "*.conf" -type f 2>/dev/null | head -10
# Find by size
echo "=== Large files (>1MB) ==="
find /var/log -type f -size +1M -exec ls -lh {} \; 2>/dev/null | head -5
# Find by modification time
echo "=== Recently modified (last 24h) ==="
find /tmp -type f -mtime -1 2>/dev/null | head -5
echo "=== Old files (>30 days) ==="
find /var/log -type f -mtime +30 -name "*.log" 2>/dev/null | head -5
# Find by permissions
echo "=== World-writable files ==="
find /tmp -type f -perm -o+w 2>/dev/null | head -5
# Find and execute
echo "=== Count lines in config files ==="
find /etc -maxdepth 1 -name "*.conf" -type f -exec wc -l {} + 2>/dev/null | tail -5
# Find with multiple conditions
echo "=== JS or TS files modified recently ==="
find . -type f \( -name "*.js" -o -name "*.ts" \) -mtime -7 2>/dev/null | head -10
# Find empty directories
echo "=== Empty directories ==="
find /tmp -maxdepth 3 -type d -empty 2>/dev/null | head -5
# Find with printf for custom output
echo "=== Formatted output ==="
find /etc -maxdepth 1 -type f -printf "%f\t%k KB\t%TY-%Tm-%Td\n" 2>/dev/null | head -5
# Find newest files
echo "=== 5 newest files ==="
find /var/log -type f -printf "%T@ %p\n" 2>/dev/null | sort -rn | head -5 | cut -d" " -f2-
# Find and process in batches with null delimiter
echo "=== Batch processing ==="
find /etc -name "*.conf" -type f -print0 2>/dev/null |
xargs -0 -I{} -P4 sh -c "echo Processing: {}; wc -l {}" 2>/dev/null | head -10
# Find with prune to exclude directories
echo "=== Exclude node_modules ==="
find . -type f -name "*.js" -not -path "*/node_modules/*" 2>/dev/null | head -10