虽然文件不包含字符串 BASH

Jac*_*ins 6 bash while-loop

我正在为我的学校制作一个脚本,我想知道如何检查文件,如果该字符串不在文件中,请执行代码,但如果是,请继续,如下所示:

while [ -z $(cat File.txt | grep "string" ) ] #Checking if file doesn't contain string
do
    echo "No matching string!, trying again" #If it doesn't, run this code
done
echo "String matched!" #If it does, run this code
Run Code Online (Sandbox Code Playgroud)

Geo*_*iou 10

您可以执行以下操作:

$ if grep "string" file;then echo "found";else echo "not found"
Run Code Online (Sandbox Code Playgroud)

做一个循环:

$ while ! grep "no" file;do echo "not found";sleep 2;done
$ echo "found"
Run Code Online (Sandbox Code Playgroud)

但要小心不要进入无限循环。必须更改字符串或文件,否则循环没有意义。

上面的 if/while 是基于命令的返回状态而不是结果来工作的。如果 grep 在文件中找到字符串将返回 0 = 成功 = true 如果 grep 未找到字符串将返回 1 = 不成功 = 假

通过使用 !我们将“假”恢复为“真”以保持循环运行,因为一旦它为真,while 就会在某些东西上循环。

更传统的 while 循环类似于您的代码,但没有无用的使用 cat 和额外的管道:

$ while [ -z $(grep "no" a.txt) ];do echo "not found";sleep 2;done
$ echo "found"
Run Code Online (Sandbox Code Playgroud)