Linux Use shell scripts to delete history log files at regular intervals

  • 2021-08-21 22:03:01
  • OfStack

1. tools directory file structure


[root@www tools]# tree tools/
tools/
 --  bin
 The    --  del_history_files
 The  
 Off-  etc
   --  del_history_files.cfg
 
2 directories, 2 files

2. Delete the history file script del_history_files


[root@www tools]# more tools/bin/del_history_files
#!/bin/sh
 
#  Delete files in the specified directory whose file time is earlier than the specified time node, time granularity: hours 
#  Configuration file format   :   Directories to clean up = Hours 
#
#
# 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. Delete the configuration file of the history file script del_history_files. cfg


[root@www tools]# more tools/etc/del_history_files.cfg
# Directories to clean up = Hours 
/home/logs/nginx=720
/home/logs/varnish=720

4. crontab can be executed


[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

Related articles: