I'm trying to capture terminal sessions in detail, such as commands and their outputs, but one challenge I've encountered is reliably obtaining the exit codes for each command. Currently, I use a small hack by injecting a marker into my PROMPT_COMMAND or precmd in Bash/Zsh that outputs something like `__TT_RC_:` before the next prompt, which I then parse. While it works, it feels a bit clunky. Are there better, more reliable methods for capturing exit codes in an interactive shell session without disrupting normal shell functionality?
3 Answers
If you just want feedback on failures, consider modifying your PS1. For instance, you could change the prompt's `$` color to red if the last command’s exit code isn’t 0. That way, you get visual cues without much hassle.
Check out this GitHub repo: https://github.com/AmalChandru/termtrace/blob/44e6be6e506064898f016bd2d9885e230a987a5b/internal/record/pty.go#L35. It may have some useful insights on capturing exit codes.
You can use `echo $?` to get the exit code of the last executed command, but the trick is automating it for each command in an interactive session. This way, you won’t need manual checks every time.

True, `$?` is good for the last command, but I'm looking for a solution that automatically logs each exit code throughout the session without requiring user input.