2

I have created a simple c program and have left off a ';' on purpose to get an error. I want using the grep command to know whether the compilation was successful or not.

I use:

gcc test.c | grep 'error' but the output does not seem right. Is this the right way ?

I am supposing it does not work because by doing:

echo "hello world" | grep "hello" I get a coloured text for the match.

When doing grep for compilation there is no such thing.

The error has this form:

test.c: In function ‘main’:
test.c:8:2: error: expected ‘,’ or ‘;’ before ‘return’
  return 0;
  ^

and the program I use is :

int main(int argc, char const *argv[]){
    char f[] = "Hello thereeee!" 
    return 0;
}
6
  • Does the compiler give the word Error with a capital?
    – Tim
    Nov 26, 2014 at 19:55
  • no , it does not .
    – billpcs
    Nov 26, 2014 at 19:59
  • Could you post the c program so I can test?
    – Tim
    Nov 26, 2014 at 19:59
  • 6
    You should be grepping the stderr: gcc ... |& grep.
    – muru
    Nov 26, 2014 at 20:03
  • 1
    Hmmm....why go about in this hard way, why not simply use the exit code from the gcc command (which is what make uses) and test that. It is far simplier.
    – mdpc
    Nov 26, 2014 at 22:43

2 Answers 2

7

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.

2

Solved by muru in comments:

You should be grepping the stderr:

gcc ... |& grep.

– muru

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .