2

I understand that I can use $? to see the exit code of the last executed command, but what if I want to identify whether I have thrown my own "exit 0" or "exit 1"?

For example:

#!/bin/bash -e    
trap "{ echo Exit code $?; exit; }" EXIT    
exit 1

If I run this script, it prints out "Exit code 0" and then exits with exit code 1. Can I access the code in the trap, or am I just going about this the wrong way? In other words, I would like this simple script to print out "Exit code 1".

Ben Flynn
  • 18,524
  • 20
  • 97
  • 142

2 Answers2

4

It's 0 because $? at the beginning of a script, where it is substituted due to the double quotes, is 0.

Try this instead:

trap '{ echo Exit code $?; exit; }' EXIT
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

Any process that terminates sets the $?, it means that it constantly will get overwritten. Save $? to a separately named var that is unique and echo that upon exit.

Edit

See Exit Shell Script Based on Process Exit Code

Community
  • 1
  • 1
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
  • I don't think this quite answers what I'm getting at. How would you change my script to incorporate your solution? – Ben Flynn May 30 '11 at 14:32
  • @Ben-Flynn Updated answer with link to SO post – Fredrik Pihl May 30 '11 at 21:40
  • I looked at that, and it would work if I called out to some command that returned with a failed exit code. It does not address what happens when I call "exit 1" myself from my script. As I mentioned, although I call "exit 1" the trap's $? show's 0, not 1. For now I decided to write my own failure function instead of calling exit, but I still would like to know if it's possible to capture the exit status that my own process is about to exit with in the trap. – Ben Flynn May 30 '11 at 21:50