1

echo $? in the following scenario does not display the return value, i.e. 1.

echo "int main() { return 1; }" > foo.c
gcc foo.c && ./a.out && echo $?

However, echo $? works when the program returns 0. Why is this?

Note: If you do another echo $? after the code above, you get the desired output 1.

3
  • 4
    Because the semantics of && is to only execute the second command if the first command returned 0.
    – celtschk
    Commented Sep 15, 2014 at 20:15
  • 4
    If you want to run your a.out program and then print the return value (a.k.a. exit status) unconditionally, use ./a.out; echo $?. Commented Sep 15, 2014 at 20:17
  • I would up vote but I don't have enough reps, thanks for the explanation and suggestion!
    – Harvinder
    Commented Sep 15, 2014 at 20:22

1 Answer 1

1

The && operator is a boolean and with short-circuit evaluation. This means that it only executes the second command if the first one is successful (i.e. it returns 0). A typical way it's used is something like this:

tar xf file.tar && rm file.tar

This only removes the file if the extraction is successful.

Your script also contains a good example of this:

gcc foo.c && ./a.out

will only try to run the program if gcc was successful.

If you want to display $? regardless of the success of a.out, you can write:

gcc foo.c && { ./a.out ; echo $? ; }

The {...} groups the command so they'll both be executed if the compilation is successful.

You must log in to answer this question.

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