Sunday 15 August 2010

linux - Why does if [ !$(grep -q) ] not work when if grep -q does? -



linux - Why does if [ !$(grep -q) ] not work when if grep -q does? -

i'm having problem getting grep work in if statement. in next code segment, if-check comes true (i.e. word not found), , programme prints not found, though words in ~/.memory.

for (( i=0; i<${#aspellwords[*]}; i++)); if [ !$(grep -q "${aspellwords[$i]}" ~/.memory) ]; words[$i]="${aspellwords[$i]}" printf "\nnot found\n" fi done

however, when test following code in place of previous segment:

for (( i=0; i<${#aspellwords[*]}; i++)); if grep -q "${aspellwords[$i]}" ~/.memory; echo found it; fi done

it works fine , finds word without issues.

so what's wrong first segment of code?

a number of things wrong first snippet.

you don't want [ ... ] if want test homecoming code. drop those.

[] not part of if syntax (as can see sec snippet).

[ shell built-in , binary on system. exits homecoming code. if ...; then tests homecoming code of ....

$() command substitution. replaces output command run.

so [ !$(grep ...) ] evaluating [ !output_from_grep ] , [ word ] interpreted [ -n word ] true whenever word non-empty. given ! never non-empty true.

simply, indicated @thom in comment (a bit obliquely), add together ! negation sec snippet space between , grep.

linux bash shell unix grep

No comments:

Post a Comment