How to use negation of a command in a while loop with grep in shell script?
-
Don't put commands inside square brackets. To loop while
grep
succeeds (i.e., until it fails), just dowhile grep ... do ︙ done
-
To loop while
grep
fails (i.e., until it succeeds), dowhile ! grep ... do ︙ done
with whitespace (i.e., one or more spaces and/or tabs) between the
!
and the command. -
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 …? You don't need the semicolon (
;
) at the end of thewhile
line (unless you put thedo
after it). In other words, thewhile
line and thedo
must be separated by a semicolon and/or one or more newlines.
Related videos on Youtube
Byakugan
Updated on September 18, 2022Comments
-
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 about 8 yearsWhat exactly you want to achieve ? Any expected output.
-