现在的位置: 首页 > 综合 > 正文

监控最新的日志文件的shell脚本

2017年12月22日 ⁄ 综合 ⁄ 共 719字 ⁄ 字号 评论关闭

好长时间没写过博客了,快荒芜了,赶紧更新个。。。

在调试大的项目脚本的时候,有时候每次运行都会产生一个新的日志文件,然后还经常出错,就要每次去找相应的新的日志文件来看看那里出问题了,非常麻烦。。。

所以这个时候脚本就会很有用了,下面的脚本就是用来监控log目录中最后被修改的文件。

#! /bin/bash

help()
{
cat<<HELP
Usage:
-p file path; default path is "log/"
-h help

HELP
exit 0
}

filebase="log/"

while [ -n $1 ]
do
  case $1 in
  -h) help;;
  -p) filebase=$2;shift 2;;
  -*) echo "input error!"; exit 1;;
  *) break;
  esac
done

dir=$(ls $filebase)
num=${#dir[*]}
newestfile=${dir[0]}

i=1
while [ $i -lt $num ]
do
  if [ "$filebase$newestfile" -ot "$filebase${dir[$i]}" ]
  then newestfile=${dir[$i]}
  fi
  i=`expr $i + 1`
done

echo "the newest log is $newestfile"

tail -f $filebase$newestfile

测试脚本:

#! /bin/bash
touch ./log/test
firsttime=`date +%s`
while true
do
  secondtime=`date +%s`
  if [ $firsttime -lt $secondtime ]
  then   echo $secondtime >> ./log/test
  firsttime=$secondtime  
  fi
done

抱歉!评论已关闭.