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.

PersianGulf
  • 10,728
  • 8
  • 51
  • 78
Harvinder
  • 395
  • 1
  • 10

1 Answers1

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.

Barmar
  • 9,648
  • 1
  • 19
  • 28