bash - 虽然文件不包含字符串 BASH

标签 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

最佳答案

你可以这样做:

$ if grep "string" file;then echo "found";else echo "not found"

做一个循环:

$ while ! grep "no" file;do echo "not found";sleep 2;done
$ echo "found"

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

上面的 if/while 是根据命令的返回状态而不是结果来工作的。 如果 grep 在文件中找到字符串,将返回 0 = success = true 如果 grep 没有找到字符串将返回 1 = 不成功 = false

通过使用!我们将“false”恢复为“true”以保持循环运行,因为 while 会在某些内容为真时立即循环。

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

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

关于bash - 虽然文件不包含字符串 BASH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42377739/

相关文章:

linux - 将变量的内容写入文件

java - 嵌套的 while 循环与条件不匹配

java - 连续打印 3 次并记录?

php - 使用 MySql Fetch Array 和 Ajax 创建可点击的链接

linux - Bash 脚本添加、删除用户?

macos - cd 到 bash 脚本中以波浪号 (~) 开头的文件夹名称

bash - 如果程序打印某些消息,如何在 bash 中继续 while 循环?

linux - 通过按特定按钮停止脚本(在脚本处理它时收听 STDIN)

javascript - 在 while 循环内正确执行 setInterval

python - python的循环问题