shell 在Linux中读取行时,不读取迭代

ia2d9nvy  于 2023-02-24  发布在  Shell
关注(0)|答案(1)|浏览(120)

我尝试解析journald
手动生成一些错误:

for i in {1..10}; do 
echo "some error #$i " | systemd-cat -p err;
done

我可以通过journalctl看到它:

journalctl -f -n 0 | grep -i 'error'
Feb 20 13:50:10 localhost [5547]: some error #1
Feb 20 13:50:10 localhost [5549]: some error #2
Feb 20 13:50:10 localhost [5551]: some error #3
Feb 20 13:50:10 localhost [5553]: some error #4
Feb 20 13:50:10 localhost [5555]: some error #5
Feb 20 13:50:10 localhost [5557]: some error #6
Feb 20 13:50:10 localhost [5559]: some error #7
Feb 20 13:50:10 localhost [5561]: some error #8
Feb 20 13:50:10 localhost [5563]: some error #9
Feb 20 13:50:10 localhost [5565]: some error #10

它可以工作,但是当我尝试在infinity while循环中使用它来在“live模式”下监听时,它不起作用:

journalctl -f -n 0 | grep -i 'error' | while read line; do echo "Error detected"; done

我怎么能这么做?谢谢!

2g32fytz

2g32fytz1#

问题是while循环在grep的输出缓冲区满之前不会获得任何输入。
最可移植的解决方法是用case语句替换grep

journalctl -f -n 0 |
while read line
do
    case $line in
        *[eE][rR][rR][oO][rR]*)
            echo "Error detected"
        ;;
    esac
done

**备注:**根据您的平台,您可以使用stdbuf -oL grep -i 'error'或bash正则表达式来代替case

相关问题