利用腳本與定時任務來清理日誌釋放磁碟空間
首先可以先了解伺服器上有哪些日誌文件
列出預設路徑底下後綴為.log的檔案
# -type f 找檔案
find /var/log -iname '*.log' -type f
列出帶有log關鍵字的資料夾
# -type d 找目錄
find ./ -name "*foo*" -type f
開始寫腳本:使用者輸入清理路徑
#!/bin/bash
# 列出系統內的文件,容量由大至小排列
cd / && du -h --max-depth=1 | sort -hr
echo "Enter directory path to clean up logs:"
read directory
cd $directory
# 只保留最近兩個月的文件,其餘刪除
find . -type f -mtime +60 -delete
echo "Log files cleanup completed!"
開始寫腳本:指定/var/log為路徑
#!/bin/bash
# 列出系统内所有文件,按大小排序
largest=$(find / -type f -exec du -Sh {} + | sort -rh | head -n 1 | awk '{ print $2 }')
# 输出最大文件路径和目录
echo "Largest file is: $largest"
# 指定日志目录
directory="/var/log"
# 进入日志目录,只保留最近两个月的日志文件
find "$directory" -type f -name "*.log" -mtime +60 -exec rm {} \;
設定為crontab定時任務
crontab -e
添加以下
0 0 * * * /path/to/腳本名稱.sh