I have the following if-then block in a Bash function declaration, using grep
and a logical OR (||):
if grep -q <somepattern> <file> || grep -q <somepattern> <file2>; then
The above works well, yay!!
But I went to "clean this up" a bit and thought this should be the same, but fails:
if [ grep -q <somepattern> <file> ] || [ grep -q <somepattern> <file2> ]; then
or
if [ grep -q <somepattern> <file> || grep -q <somepattern> <file2> ]; then
I get this error:
-bash: [: missing `]'
grep: ]: No such file or directory
I thought that not using [[ $(<foo>) ]]
syntax would be safe and reduce clutter, but it is not clear to me why this does not work. Have googled around a bit and it still unclear to me why this fails.
as an interesting side note, this is ok:
if [ $(grep -q <somepattern> <file>) ] || [ $(grep -q <somepattern> <file2>) ]; then
my thinking was the $(..)
wrapping the grep statements is overkill as the [..]
would be looking for the return from grep.
I set -x
to get some clues and I see this:
+ '[' grep -q <somepattern> <file> ']'
-bash: [: too many arguments
+ '[' grep -q <somepattern> <file2> ']'
-bash: [: too many arguments
My understanding of test
leads me to believe this should work, obviously not. Though maybe this has to do with the observation that test
will not execute the grep command inside [..]
or [[..]]
blocks, hence success with grep
enclosed in $(..)
syntax
Anyone want to shed a bit more light onto this for me?