Linux使用shell腳本定時刪除歷史日志文件
更新時間:2020年08月24日 10:29:44 作者:邯鄲-小刀
這篇文章主要介紹了Linux使用shell腳本定時刪除歷史日志文件,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
1、tools目錄文件結(jié)構(gòu)
[root@www tools]# tree tools/ tools/ ├── bin │ ├── del_history_files │ └── etc ├── del_history_files.cfg 2 directories, 2 files
2、刪除歷史文件腳本 del_history_files
[root@www tools]# more tools/bin/del_history_files #!/bin/sh # 刪除指定目錄下,文件時間早于指定時間節(jié)點的文件,時間粒度:小時 # 配置文件格式 : 需清理的目錄=小時數(shù) # # # define restricted path PATH="/bin:/usr/bin:/sbin:/usr/sbin" # adirname - return absolute dirname of given file adirname() { odir=`pwd`; cd `dirname $1`; pwd; cd "${odir}"; } # --------- # constants # --------- MYNAM=`basename "$0"` MYDIR=`adirname "$0"` MYCFG="${MYDIR}/../etc/${MYNAM}.cfg" MYTMP="${MYDIR}/../tmp" MYLCK="${MYTMP}/${MYNAM}.lock" # perform some locking (as good as it gets in a shell) [ -s "${MYLCK}" ] && kill -0 `cat "${MYLCK}"` 2>/dev/null && die "${MYNAM}: already running!" echo "$$" > "${MYLCK}" PATHS=(`cat ${MYCFG}`) for PP in ${PATHS[@]} do APP_PATH=`echo ${PP} | awk -F'=' '{print $1}'` N=`echo ${PP} | awk -F'=' '{print $2}'` if [ -d ${APP_PATH} ] ; then T=`/bin/date --date "${N} hours ago" "+%Y%m%d%H%M"` TMP_FILE="/tmp/`echo ${PP} | md5sum | awk '{print $1}'`" touch -t ${T} ${TMP_FILE} find ${APP_PATH} ! -newer ${TMP_FILE} -type f -print0 | xargs -0 -n 100 rm -rf find ${APP_PATH} -type d -empty -print0 | xargs -0 -n 100 rm -rf &> /dev/null fi done rm -rf ${MYLCK}
3、刪除歷史文件腳本的配置文件 del_history_files.cfg
[root@www tools]# more tools/etc/del_history_files.cfg #需清理的目錄=小時數(shù) /home/logs/nginx=720 /home/logs/varnish=720
4、crontab 執(zhí)行即可
[root@www tools]# more /etc/crontab SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/ #clear old logs 00 6 * * * root /home/tools/bin/del_history_files
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
linux或windows環(huán)境下pytorch的安裝與檢查驗證(解決runtimeerror問題)
這篇文章主要介紹了linux或windows環(huán)境下pytorch的安裝與檢查驗證(解決runtimeerror問題),需要的朋友可以參考下2019-12-12Centos8下django項目部署 nginx+uwsgi的教程
這篇文章主要介紹了Centos8下django項目部署 nginx+uwsgi的教程,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05Linux服務(wù)器磁盤空間占用情況分析與清理指南(解決方法)
為防止節(jié)假日期間服務(wù)器磁盤占用過高引起報警,需在節(jié)前檢查并清理磁盤,檢查條件包括使用率超90%、剩余空間不足30G等,通過shell腳本自動判斷并輸出異常信息,腳本及使用方法詳細介紹,感興趣的朋友一起看看吧2024-09-09