2

Is there any way to use while loop and grep all together? See my example:

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

It says:

./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}) ]];'
Byakugan
  • 145
  • What exactly you want to achieve ? Any expected output. – Pacifist Mar 02 '16 at 03:19
  • From this to work ... When grep does not find a specific text wait for another script to try complete its task to add this text and repeat every 10 seconds till its done and text is present... – Byakugan Mar 02 '16 at 03:21

1 Answers1

5
  1. Don't put commands inside square brackets.  To loop while grep succeeds (i.e., until it fails), just do

    while grep ...
    do
        ︙
    done
    
  2. To loop while grep fails (i.e., until it succeeds), do

    while ! grep ...
    do
        ︙
    done
    

    with whitespace (i.e., one or more spaces and/or tabs) between the ! and the command.

  3. You should always quote your shell variable references (e.g., "$path") unless you have a good reason not to, and you’re sure you know what you’re doing.  By contrast, while braces can be important, they’re not as important as quotes, so "$text" and "$path" are good enough (you don't need to use "${text}" and "${path}", in this context).

    … unless path might be set to a list of filenames, in which case, see Security implications of forgetting to quote a variable in bash/POSIX shells  — But what if …?

  4. You don't need the semicolon (;) at the end of the while line (unless you put the do after it).  In other words, the while line and the do must be separated by a semicolon and/or one or more newlines.