作为IT工程师,清理大文件是系统维护的常见任务。以下是一套完整的解决方案,使用各种Linux工具来高效识别、分析和清理大文件。
find
命令# 查找大于100MB的文件
find / -type f -size +100M -exec ls -lh {} \;
# 查找大于1GB的文件并按大小排序
find / -type f -size +1G -exec du -h {} + | sort -rh
ncdu
工具# 安装ncdu
sudo apt install ncdu # Debian/Ubuntu
sudo yum install ncdu # RHEL/CentOS
# 扫描目录
ncdu /path/to/directory
du
命令# 查看当前目录下各子目录大小
du -h --max-depth=1 | sort -h
# 查看前10大目录
du -ah / | sort -rh | head -n 10
file
命令识别文件类型file /path/to/largefile
head
/tail
查看文件内容head -n 100 /path/to/largefile # 查看前100行
tail -n 100 /path/to/largefile # 查看后100行
less
查看大文件less /path/to/largefile
# 普通删除
rm /path/to/largefile
# 安全删除(多次覆盖)
shred -vzu -n 5 /path/to/largefile
# 保留文件但清空内容(对日志文件特别有用)
truncate -s 0 /path/to/largefile
# 或
> /path/to/largefile
#!/bin/bash
# 查找并删除超过30天且大于100MB的日志文件
find /var/log -type f -name "*.log" -size +100M -mtime +30 -exec rm -f {} \;
# 查找并压缩超过30天且大于50MB的日志文件
find /var/log -type f -name "*.log" -size +50M -mtime +30 -exec gzip {} \;
lsof
查找被进程占用的大文件# 查找已删除但仍被进程占用的文件
lsof +L1
fallocate
创建/缩减大文件# 创建1GB的稀疏文件
fallocate -l 1G /path/to/file
# 缩减文件到500MB
truncate -s 500M /path/to/file
rsync
清理目录# 清空目录(比rm -rf更安全)
mkdir empty_dir
rsync -a --delete empty_dir/ target_dir/
rmdir empty_dir
# 为用户设置磁盘配额
setquota -u username 500M 1G 0 0 /
# 编辑/etc/logrotate.conf配置日志轮转
/var/log/myapp.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
size 100M
}
# 使用df监控
watch -n 60 df -h
# 设置cron作业监控
echo '0 * * * * /usr/bin/df -h > /var/log/disk_usage.log' | sudo tee -a /etc/crontab
通过以上工具和方法的组合,您可以高效地识别、分析和清理Linux系统中的大文件,保持系统整洁和高效运行。