Search code examples
bashshellunixexit-code

Record exit codes of all shell commands as they are executed


I would like to record the exit code of all shell commands from a specific TTY without additional syntax per command.

For example:

> source solution.sh # sets up this bash session to monitor exit codes
> ls
> ls f
ls: f: No such file or directory
> echo "hello world"

Some file would store exit codes:

0
1
0

Is this possible? If not, I am open to other ideas that might accomplish something similar.

My end goal is to collect data on all of my executed commands and their exit codes (kind of like ~/.bash_history with exit codes appended)


Solution

  • Thanks to the numerous helpful comments, I have arrived at the following solutions to record exit codes of shell commands as they are executed:

    1. Using trap debug:

       trap 'x=$?; echo "$x" >> ~/exit-codes.log' DEBUG
      
    2. Using PROMPT_COMMAND:

       PROMPT_COMMAND='x=$?; echo "$x" >> ~/exit-codes.log; (exit $x)'
      

      Note that the PROMPT_COMMAND must exit with the exit code in order to preserve exit code history across shell commands.

    3. Process accounting is a more principled solution for this, but it requires sudo access to enable.

    The solution.sh I ended up using to log both exit codes and commands is the following:

    trap 'previous_exit_code=$?; previous_command=$this_command; \
      this_command=$BASH_COMMAND; [ ! -z "$previous_command" ] && \ 
      echo \"$previous_command\", $previous_exit_code >> ~/exit-codes.log' DEBUG