运行bash命令后没有收到grep输出的电子邮件

时间:2017-06-19 15:16:26

标签: bash shell unix

我有下面的代码,它不会将grep输出发送到电子邮件,但它会显示输出命令行。不确定我做错了什么

sudo tail -f  /path/to/file | while read line ; do 
    egrep 'successfully started \[[0-9] out of [0-9]\] components|successfully started \[[0-9] out of [0-9]\] components' 
    if [ $? -eq 0 ]; then
        (echo " RESTARTS"; echo; echo $line) | mail -s "RESTART" email@email.com
    else
        echo " FAILS"
    fi
done

[UPDATE]

还有另一种方法,我试图这样做,但它不会发送电子邮件..我只是确保我可以摆脱循环而不是永远,所以这就是为什么我把尾巴放进去

while read line; do

    echo "$line" | sudo tail -f  /opt/bmc/ao/cdp/tomcat/logs/grid.log

    if [ $(echo "$line" | grep -E 'successfully started \[[0-9] out of [0-9]\] components|successfully started \[[0-9] out of [0-9]\] components' | wc -l) -ne 0 ]; then
        (echo "CDP RESTARTS"; echo; echo "$line") | mail -s "BAOCDP AUTO RESTART" noreply@google.com

        break
    fi

done 

1 个答案:

答案 0 :(得分:0)

grep无法猜测您希望它对$line变量的内容起作用,您必须将其提供给命令:

egrep 'successfully started \[[0-9] out of [0-9]\] components|successfully started \[[0-9] out of [0-9]\] components' <<< "$line"

echo "$line" | egrep 'successfully started \[[0-9] out of [0-9]\] components|successfully started \[[0-9] out of [0-9]\] components'

关于你的编辑,我会使用以下代码:

sudo tail -f  /opt/bmc/ao/cdp/tomcat/logs/grid.log | while read line; do

    if $(echo "$line" | grep -E 'successfully started \[[0-9] out of [0-9]\] components|successfully started \[[0-9] out of [0-9]\] components'); then
        (echo "CDP RESTARTS"; echo; echo "$line") | mail -s "BAOCDP AUTO RESTART" noreply@google.com

        break
    fi

done

除了放回它所属的tail之外,我还简化了if的条件:grep当且仅当它匹配时才会返回1,因此可以使用它作为条件本身。