用于在特定时间间隔内复制 /tmp 目录中的日志文件的 shell 脚本



我想编写一个 shell 脚本,将 1 小时内生成的日志文件复制到/tmp 目录。我想在 cron 中安排此脚本,以便此作业可以每小时运行一次,并将新生成的日志文件复制到/tmp 中。

谢谢

你把一个文件作为一个参数,它向你显示正在发生的日志......您可以更改脚本以从标准输出重定向到文件...

#!/bin/bash
GAP=10     #How long to wait
LOGFILE=$1 #File to log to
if [ "$#" -ne "1" ]
then
    echo "USAGE: ./watch-log.sh <file with absolute path>"
    exit 1
fi

#Get current long of the file
len=`wc -l $LOGFILE | awk '{ print $1 }'`
echo "Current size is $len lines."
while :
do
    if [ -N $LOGFILE ] 
    then
        echo "`date`: New Entries in $LOGFILE: "
        newlen=`wc -l $LOGFILE | awk ' { print $1 }'`
        newlines=`expr $newlen - $len`
        tail -$newlines $LOGFILE
        len=$newlen
    fi
    sleep $GAP
done
exit 0

使用 find 命令将能够实现上述目标,假设/tmp 不在搜索路径中日志文件具有.log扩展名

find $PATH_TO_SEARCH -type f -name "*.log" -cmin -60 -exec cp {} /tmp ;
# Above single command can be configured as cron job.

最新更新