Bash:如何在连续循环中拖尾最新文件

时间:2018-10-02 14:05:40

标签: bash tail scraper

我正在尝试编写监视日志文件的脚本,并在发生特定错误时执行某些功能。 我得到了主要的代码,但是遇到了一个问题。 当系统日期更改(日志文件名称模式为LOG.NODE1.DDMMYYYY)时,应用程序创建新的日志文件,如何获取代码以自动切换到创建的新文件。以下是我到目前为止的脚本,

#!/bin/sh

logfile=$(ls -t $DIR"/env/log/LOG"* | head -n 1)
echo $logfile
tail -f $logfile | while read LOGLINE
do

if [[  "${LOGLINE}" == *";A database exception has occurred: FATAL DBERR:  SQL_ERROR: ORA-00001: unique constraint (IX_TEST1) violated"* ]];

then
        #Do something

fi
done

1 个答案:

答案 0 :(得分:0)

#!/bin/bash
#      ^^^^ -- **NOT** /bin/sh

substring=";A database exception has occurred: FATAL DBERR:  SQL_ERROR: ORA-00001: unique constraint (IX_TEST1) violated"
newest=
timeout=10  # number of seconds of no input after which to look for a newer file

# sets a global shell variable called "newest" when run
# to keep overhead down, this avoids invoking any external commands
find_newest() {
  set -- "${DIR?The variable DIR is required}"/env/log/LOG*
  [[ -e $1 || -L $1 ]] || return 1
  newest=$1; shift
  while (( $# )); do
    [[ $1 -nt $newest ]] && newest=$1
    shift
  done
}

while :; do
  find_newest  # check for newer files
  # if the newest file isn't the one we're already following...
  if [[ $tailing_from_file != "$newest" ]]; then
    exec < <(tail -f -- "$newest")  # start a new copy of tail following the newer one
    tailing_from_file=$newest       # and record that file's name
  fi
  if read -t "$timeout" -r line && [[ $line = *"$substring"* ]]; then
    echo "Do something here"
  fi
done