如何在shell脚本中使用grep在while循环中使用命令的否定?

Bya*_*gan 2 grep bash shell-script test

有什么方法可以同时使用 while 循环和 grep 吗?看我的例子:

while  [[  !(grep -R -h "${text}" ${path}) ]];
do
    ...
done
Run Code Online (Sandbox Code Playgroud)

它说:

./test_script.sh: line 1: conditional binary operator expected
./test_script.sh: line 1: expected `)'
./test_script.sh: line 1: syntax error near `-R'
./test_script.sh: line 1: `while  [[  !(grep -R -h "${text}" ${path}) ]];'
Run Code Online (Sandbox Code Playgroud)

G-M*_*ca' 5

  1. 不要将命令放在方括号内。要循环 whilegrep成功(即,直到失败),只需执行

    while grep ...
    do
        ?
    done
    
    Run Code Online (Sandbox Code Playgroud)
  2. 要在grep失败时循环(即,直到成功),请执行

    while ! grep ...
    do
        ?
    done
    
    Run Code Online (Sandbox Code Playgroud)

    !和命令之间有空格(即一个或多个空格和/或制表符)。

  3. 您应该始终引用您的 shell 变量引用(例如,"$path"),除非您有充分的理由不这样做,并且您确定您知道自己在做什么。相比之下,虽然大括号很重要, 但它们不如引号重要,因此"$text"and"$path"已经足够好了(在这种情况下,您不需要使用"${text}"and "${path}")。

    ...除非path可能设置为文件名列表,在这种情况下,请参阅 忘记在 bash/POSIX shell 中引用变量的安全隐患?——但万一呢?……?

  4. 您不需要;在行尾使用分号 ( ) while(除非您将分号放在它do之后)。换句话说,whileline 和 thedo必须用分号和/或一个或多个换行符分隔。