3

On OS X, Linux, and other systems, you can use $? to get the exit code of the last command. Is there any way to exit codes of older commands? Either by saying "give me the exit code of the nth previous command" or by saying "give me the exit code of the process with PID p"?

1
  • you can append the exit codes yourself to a file after issuing commands
    – user373230
    Oct 16, 2014 at 10:29

1 Answer 1

3

The exit code of a command is output only once, and if not processed further the only thing that saves that exit code is the shell. bash only saves the exit code for the last command.

In order to look up the exit code of older commands you need to save them to a variable, like so:

$ echo "This command will succeed"
$ exitcode=$?

...

$ echo $exitcode
0
2
  • Thanks for the answer. Can you point me to some documentation that verifies bash only saves the last exit code? Oct 16, 2014 at 15:12
  • 1
    I can't find anything explicitly stating so, but exit statuses by nature are lost unless explicitly saved. In man bash under "Special Parameters" we find the definition for $? Expands to the exit status of the most recently executed foreground pipeline. There is no mention of looking up old exit statuses in bash manual.
    – Arkenklo
    Oct 17, 2014 at 9:17

You must log in to answer this question.

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