How to use negation of a command in a while loop with grep in shell script?

5,227
  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.

Share:
5,227

Related videos on Youtube

Byakugan
Author by

Byakugan

Updated on September 18, 2022

Comments

  • Byakugan
    Byakugan over 1 year

    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}) ]];'
    
    • Pacifist
      Pacifist about 8 years
      What exactly you want to achieve ? Any expected output.