我想创建一个脚本,用于在正在写入的日志文件中查找特定字符串。我想获取第一个结果并将其放入变量中以备后用。这将通过 SSH 连接使用,如下所示:
ssh 'user@xxx.xxx.xxx.xxx' 'bash -s' < /usr/local/bin/checklog.sh string
常规终端中的命令
tail -f /var/log/named.log | grep $1 > $var
echo "${var}"
当我尝试上述方法时,没有输出
最佳答案
使用 while
循环可能适合您的情况,但请注意,它不能保证捕捉到日志文件的每一行。考虑这样一种情况,日志写入器包含一个写出两行的操作:
Something bad just happened:\nError xyz on line 22
很可能您的循环在执行 tail -1
操作时只会看到第二行。
不仅如此,while 循环实现还意味着您在循环中旋转 CPU,不断触发 tail
命令(看看 top
而 while
实现运行,而不是 tail -f
)。
This question如果您只想在模式匹配后停止监视,有一些好的建议。 (注意尾部进程的问题。)
这个怪物可能不是最优的,但它捕获每一行,在等待新行时使用最少的 CPU,在完成时终止尾部,并让您可以灵活地编写一些额外的逻辑(比如根据不同的执行操作匹配的模式):
watchPattern=$1
logFile=/var/log/named.log
logLine=""
while read -r logLine ; do
#Do we have a match?
if [[ "$logLine" == *"$watchPattern"* ]] ; then
#Confirmation message, written to console (for example, not needed)
echo "Found a match."
#Kill off the tail process (a bit of a hack that assumes one at a time)
kill $(ps -eo pid,command | awk -v pattern="tail -fn0 $logFile" '$0 ~ pattern && !/awk/ {print $1}')
#Get out of here
break
fi
done< <(exec tail -fn0 "$logFile")
#logLine will be the matched value
echo "match = $logLine"
关于linux - 在 bash 脚本中使用 grep 在日志文件上使用 tail -f,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30787575/