1

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)

ben-albrecht
  • 1,785
  • 10
  • 23

2 Answers2

0

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=$?; $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
ben-albrecht
  • 1,785
  • 10
  • 23
  • 1
    You can write `PROMPT_COMMAND='x=$?; echo $x >> ~/exit-codes.log; (exit $x)'` to preserve the exit status. – chepner Jun 04 '20 at 20:46
  • @chepner - oh nice. Any other advantages to using PROMPT_COMMAND over trap DEBUG beyond conciseness? – ben-albrecht Jun 04 '20 at 20:48
  • 1
    It's not really any more concise; I just used shorter variable names :) – chepner Jun 04 '20 at 20:55
  • With `PROMPT_COMMAND='x=$?; echo x${x}x >> ~/exit.txt'`, I can do in my shell: `(exit 42)` followed by `echo $?` which prints 42. That's without the `(exit $x)` in bash 4.4.19(1). – Philippe Carphin Aug 17 '23 at 19:35
-1

The last exit code is stored in the $? variable.

But then you have to check it for each issued commands so that still needs some glue to achieve your goal I guess.

antoine
  • 1,653
  • 11
  • 23
  • Yes, the glue is the part I was trying to figure out here. I have posted a solution based on feedback in the comments. – ben-albrecht Jun 04 '20 at 20:36