1

I want to get an exit code only if a specific text is found in a set of log file.

If no matches are found, or no files are present the command should pass successfully.

Grep should be silent, as I don't want to see the matches. I only want to know if the pattern was found (using exit code).

Somehow it seems that if use quiet mode to silence grep, the result code will always be success.

1
  • 1
    grep --silent hm /etc/passwd returns 1, as expected. If that's not working for you, you can always discard stdout/stderr.
    – PesaThe
    Commented Jan 5, 2018 at 14:18

2 Answers 2

1

Works for me

mkdir _ ; cd _ ; touch a ; echo b > b
grep -q c * || echo $?
1

0 means success, 1 means no matches. In a condition, you don't need the $?, you can use the command directly:

if grep -q c * ; then
    echo Found
else
    echo Not found
fi
0

Solution was to just use ! grep ... >/dev/null.

1
  • 1
    0 status is success, unlike in languages like C. Isn't that the source of your confusion? Otherwise what is the reason for ! ?
    – PesaThe
    Commented Jan 5, 2018 at 15:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.