如何等待特定行出现在文件中

时间:2014-09-21 13:48:57

标签: bash shell unix

是否可以编写一个在特定文件中出现特定行之前不会继续的脚本?

例如,我想做这样的事情:

CANARY_LINE='Server started'
FILE='/var/logs/deployment.log'

echo 'Waiting for server to start'
.... watch $FILE for $CANARY_LINE ...
echo 'Server started'

基本上是一个shell脚本,它监视文件的行(或正则表达式)。

4 个答案:

答案 0 :(得分:14)

tail -f path_to_my_log_file.log | sed '/particular_line/ q'

答案 1 :(得分:1)

我们必须小心循环。

例如,如果要检查文件以启动算法,则可能需要执行以下操作:

  FILE_TO_CHECK="/var/logs/deployment.log"
  LINE_TO_CONTAIN="Server started"
  SLEEP_TIME=10
  while [ $(cat FILE_TO_CHECK | grep "${LINE_TO_CONTAIN}") ]
  do
      sleep ${SLEEP_TIME}
  done

  # Start your algorithm here

但是,为了防止无限循环,你应该添加一些绑定:

  FILE_TO_CHECK="/var/logs/deployment.log"
  LINE_TO_CONTAIN="Server started"
  SLEEP_TIME=10
  COUNT=0
  MAX=10
  while [ $(cat FILE_TO_CHECK | grep "${LINE_TO_CONTAIN}") -a ${COUNT} -lt ${MAX} ]
  do
      sleep ${SLEEP_TIME}
      COUNT=$(($COUNT + 1))
  done

  if [ ! $(cat FILE_TO_CHECK | grep "${LINE_TO_CONTAIN}") ]
  then
    echo "Let's go, the file is containing what we want"
    # Start your algorithm here
  else
    echo "Timed out"
    exit 10
  fi

答案 2 :(得分:0)

CANARY_LINE='Server started'
FILE='/var/logs/deployment.log'

echo 'Waiting for server to start'
grep -q $CANARY_LINE <(tail -f $FILE)
echo 'Server started'

来源:改编自How to wait for message to appear in log in shell

答案 3 :(得分:-1)

试试这个:

#!/bin/bash

canary_line='Server started'
file='/var/logs/deployment.log'

echo 'Waiting for server to start'

until grep -q "${canary_line}" "${file}"
do
  sleep 1s
done

echo 'Server started'

根据您的喜好调整sleep参数。

如果文件中的行需要与完全匹配,即整行,请将grep的第二个参数更改为"^${canary_line}$"

如果该行包含grep认为特殊的任何字符,那么您将不得不以某种方式解决该问题。