bash 错误的尾部语法或 grep 命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26737639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:41:58  来源:igfitidea点击:

Faulty tail syntax or grep command?

bash

提问by Andy Kendall

I've been given the following code:

我得到了以下代码:

tail -fn0 /var/log/messages | \  
while read line ; do  
       echo "$line" | grep "test"  
       if [ $? = 0 ]  
       echo "Running information gathering"  
       then  
etc...etc  

What it's supposed to do is continually monitor the added lines of the "/var/tmp/messages" file and if one contains the word "test" then execute the rest of the script and exit when done.
It's executing the rest of the script as soon as anyline is added to the messages file, irrespective of line content. I've added echo commands, and $line contains the new log file line correctly. I've tried changing the test "$? = 0" to "$? = 1" but it makes no difference.
Could someone please give me a pointer?

它应该做的是持续监视“/var/tmp/messages”文件的添加行,如果其中包含“test”一词,则执行脚本的其余部分并在完成后退出。
只要将任何行添加到消息文件中,它就会执行脚本的其余部分,而不管行的内容如何。我添加了 echo 命令,并且 $line 正确包含了新的日志文件行。我尝试将测试“$? = 0”更改为“$? = 1”,但没有任何区别。
有人可以给我一个指针吗?

Thanks @TomFenech

谢谢@TomFenech

回答by Tom Fenech

I would suggest that instead of using a loop, you can make things a lot simpler by just using grep:

我建议不要使用循环,您可以通过使用 grep 使事情变得更简单:

tail -fn0 /var/log/messages | grep -q test
echo "Running information gathering"
# rest of script

grep -qexits after the first match, so your script will continue as soon as the first match is found.

grep -q在第一场比赛后退出,因此一旦找到第一场比赛,您的脚本就会继续。

回答by anubhava

In BASH you can use glob matches and avoid grep:

在 BASH 中,您可以使用 glob 匹配并避免grep

tail -fn0 /var/log/messages | 
while read -r line; do  
    if [[ "$line" == *test* ]]; then
       echo "Running information gathering"  
    fi  
done

PS:You could use grep -qinstead to get correct exit status based on the successful match being found.

PS:您可以改用grep -q根据找到的成功匹配来获取正确的退出状态。