If you would like to know whether a command has succeeded or failed, you usually have to check its exit code. Zero indicates success, non-zero shows failure.
Example in shell:
gcc foo.c
rc=$? # Store exit code for later use
if [ $rc -ne 0 ]; then # $rc not equal to zero
echo "gcc exited with $rc"
fi
You could also use &&
or ||
to execute a command on success or failure, respectively:
gcc foo.c && echo gcc succeeded
gcc foo.c || echo gcc failed
As mentioned in the comments, gcc foo.c | grep error
did not catch everything because a pipe normally catches the standard output (stdout) only. Programs will often output exceptional messages to standard error (stderr). To catch that stream, you have to redirect stderr to stdout before piping to grep
:
gcc foo.c 2>&1 | grep error
Or, if you use the bash
shell, you can use this shorthand:
gcc foo.c |& grep error
Now, this gcc
generates an a.out
binary. If you just want to check for syntax errors, you can use gcc -fsyntax-only foo.c
. You can then examine at the output or check its exit code for errors.
Best Answer
grep
itself only has options for context based on lines. An alternative is suggested by this SU post:As another alternative, I'd suggest
fold
ing the text and then grepping it, for example:The
-s
option will makefold
push words to the next line instead of breaking in between.Or use some other way to split the input in lines based on the structure of your input. (The SU post, for example, dealt with JSON, so using
jq
etc. to pretty-print andgrep
... or just usingjq
to do the filtering by itself ... would be better than either of the two alternatives given above.)This GNU awk method might be faster:
-v RS=...
), and the number of characters in context (-v n=...
)FNR > 1
) is one where awk found a match for the pattern.n
trailing characters from the previous line (p
) andn
leading characters from the current line (substr($0, 0, n)
), along with the matched text for the previous line (which isprt
)p
andprt
after printing, so the value we set is used by the next lineRT
is a GNUism, that's why this is GNU awk-specific.For recursive search, maybe: