Exit status of commands before last command

0

1

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"?

Amit Kumar Gupta

Posted 2014-10-16T10:23:40.977

Reputation: 163

you can append the exit codes yourself to a file after issuing commands – None – 2014-10-16T10:29:26.097

Answers

1

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

Arkenklo

Posted 2014-10-16T10:23:40.977

Reputation: 311

Thanks for the answer. Can you point me to some documentation that verifies bash only saves the last exit code? – Amit Kumar Gupta – 2014-10-16T15:12:04.960

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 – 2014-10-17T09:17:32.567