BASH更好的监控文件的方法

时间:2013-07-19 14:01:17

标签: bash logging monitoring

我制作了一个Bash脚本来监视某些服务器日志文件中的某些数据,而我的方法可能不是最有效的。

我特别想知道的一个问题是我必须在受监控的日志中写一个换行符,以便不断读取同一行。

反馈将非常感谢!

#!/bin/bash

serverlog=/home/skay/NewWorld/server.log
onlinefile=/home/skay/website/log/online.log
offlinefile=/home/skay/website/log/offline.log
index=0

# Creating the file
if [ ! -f "$onlinefile" ]; then
    touch $onlinefile
    echo "Name                  Date            Time" >> "$onlinefile"
fi
if [ ! -f "$offlinefile" ]; then
    touch $offlinefile
    echo "Name                  Date            Time" >> "$offlinefile"
fi

# Functions
function readfile {

# Login Variables
loginplayer=`tail -1 $serverlog | grep "[INFO]" | grep "joined the game" | awk '{print $4}'`
logintime=`tail -1 $serverlog | grep "[INFO]" | grep "joined the game" | awk '{print $2}'`
logindate=`tail -1 $serverlog | grep "[INFO]" | grep "joined the game" | awk '{print $1}'`

# Logout Variables
logoutplayer=`tail -1 $serverlog | grep "[INFO]" | grep "left the game" | awk '{print $4}'`
logouttime=`tail -1 $serverlog | grep "[INFO]" | grep "left the game" | awk '{print $2}'`
logoutdate=`tail -1 $serverlog | grep "[INFO]" | grep "left the game" | awk '{print $1}'`

# Check for Player Login
    if [ ! -z "$loginplayer" ]; then
        echo "$loginplayer          $logindate  $logintime" >> "$onlinefile"
        echo "Player $loginplayer login detected" >> "$serverlog"
        line=`grep -rne "$loginplayer" $offlinefile | cut -d':' -f1`
        if [ "$line" > 1 ]; then
            sed -i "$line"d $offlinefile
            unset loginplayer
                    unset line
        fi
    fi
# Check for Player Logout
    if [ ! -z "$logoutplayer" ]; then
        echo "$logoutplayer         $logoutdate $logouttime" >> "$offlinefile"
        echo "Player $loginplayer logout detected" >> "$serverlog"
        line=`grep -rne "$logoutplayer" $onlinefile | cut -d':' -f1`
        if [ "$line" > 1 ]; then
            sed -i "$line"d $onlinefile
            unset logoutplayer
            unset line
        fi
    fi
}

# Loop
while [ $index -lt 100 ]; do
    readfile
done

谢谢!

1 个答案:

答案 0 :(得分:0)

而不是使用多个

tail -n 1 file

尝试以下构造:

tail -f file | while read line;do
   echo "read: $line"
done

它会更可靠......并且不会两次读同一行;)

注意:通过使用grep / awk / etc的新进程,你正在烧掉进程...并不是它很重要,但通常进程创建很昂贵......但是如果很少出现新行,那就非常好了

我想要得到的是:如果你有兴趣,请看看bash构建字符串操纵器函数替换$(x / aa} $ {x // aa}和朋友..或尝试使用扩展的正则表达式用grep