一旦找不到字符串,如何在 shell 中停止?

how to stop while do in shell once a string is not found?

我有这个脚本:

#!/bin/bash
while [ true ]
do

    if tail -1 /tmp/test | grep 'line3'
    then
        echo found
        sleep 5
    else
        echo not found
    fi
done

它每 5 秒查找一次 line3。一旦找不到 line3,如何让脚本停止?

已解决

    #!/bin/bash
while [ true ]
do

    if tail -1 /tmp/test | grep 'line3'
    then
        echo found
        sleep 5
    else
        echo not found
        break
    fi
done

使用逻辑中断。不用破解。

#!/bin/bash

match=1

while [ ${match} -eq 1 ]
do

    if tail -1 /tmp/test | grep 'line3'
    then
        echo found
        sleep 5
    else
        match=0
        echo not found
    fi
done

有点不清楚为什么要在 tail | grepif, then, else 周围包含 while [ true ],因为 while 循环可以使用您的子句作为测试本身:

#!/bin/bash

while tail -1 /tmp/test | grep 'line3'
do
    echo found
    sleep 5
done

echo "not found"

if, then, else 包装在 while [ true ] 中并没有错,只是不够理想。