1、tools目錄文件結構
[root@www tools]# tree tools/ tools/ ├── bin │ └── gzip_history_files └── etc └── gzip_history_files.cfg 2 directories, 2 files
2、壓縮歷史文件腳本 gzip_history_files
[root@www tools]# more tools/bin/gzip_history_files #!/bin/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 ! -name '*.gz' | xargs gzip > /dev/null 2> /dev/null fi done rm -rf ${MYLCK}
3、壓縮歷史文件腳本配置文件gzip_history_files.cfg
[root@www tools]# more tools/etc/gzip_history_files.cfg #需壓縮的目錄=小時數 /home/logs/nginx=72 /home/logs/varnish=72
4、配置計划任務
[root@www tools]# more /etc/crontab SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/ # gzip old logs 03 05 * * * root /home/tools/bin/gzip_history_files
以上會每天5點03分壓縮配置文件目錄中的3天前的文件。