退出while循环时出错

时间:2014-02-21 15:32:12

标签: shell

我通过shell脚本监视日志文件,一旦字符串匹配,我想退出。我正在使用while语句来读取日志文件。但问题是我的脚本永远不会退出它打印我期望但永远不会退出的字符串。下面是我的剧本

tail -fn0 $TOMCAT_HOME/logs/catalina.out | \
while read line ; do
echo "$line" | grep "Starting ProtocolHandler" 
if [ $? = 0 ]
then
exit
fi 
done

尝试使用grep -q,但无法解决问题

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

您可以使用grep -q

tail -fn0 $TOMCAT_HOME/logs/catalina.out | grep -q "Starting ProtocolHandler"

第一次出现字符串"Starting ProtocolHandler"

后会立即退出

答案 1 :(得分:0)

您只想要行号吗? grep -n怎么样?那你甚至不需要一个脚本。

   -n, --line-number
          Prefix each line of output with the line number within its input file.

与-m结合,让它在1场比赛后退出

   -m NUM, --max-count=NUM
          Stop reading a file after NUM matching lines.  If the input is standard input from a regular file, and  NUM  matching  lines  are  output,  grep ensures  that  the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines.  This enables a calling process to resume a search.  When grep stops after NUM matching  lines,  it  outputs  any  trailing  context lines.  When the -c or --count option is also used, grep does not output a count greater than NUM.  When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines.

所以,你有类似

的东西
grep -n -m 1 "Starting ProtocolHandler" [filename]

如果您想要退出:

cat [filename] | grep -n -m 1 "Starting ProtocolHandler"