0

Here is what I am trying to achieve:

I am trying to write a script that for every command the user is executing in Bash will save the following to a file:

  1. The full command that the user typed
  2. The exit code of the command (AFAIK script doesn't provide this)
  3. Content of the stdout and stderr that the command produced.

I was able to implement both 1 and 2 very quickly using the https://github.com/rcaloras/bash-preexec

I am stuck with 3.

I want to create a script that I can put in ~/.bash_profile for easy setup.

Thanks in advance!

Guss
  • 12,628
Ikaso
  • 101

1 Answers1

0

As explained here you can use exec and &> redirection with tee to capture standard output and standard error to a file.

One thing I'm wondering about is whether you want to have a different capture per command (as can be understood from your requirement for "every command" and the assertion that script cannot be used) or whether you just want to capture an entire session in a log file.

If its the latter, then running script at the beginning of the session and then implementing whatever else you did inside that should work fine, but the above linked answer would also help. If you do want a different file for every command, then you'd probably want to implement something that triggers in the command prompt - possibly by implementing $PROMPT_COMMAND (man bash for more details) and replaces the log file for each command.

Please note that as exec &> captures the standard streams into a file, it basically disables and TTY applications (that draw on the screen) from running (such as less or mc). This will be true for any shell level console capture tool, unless it does a full TTY emulation (as script does, I believe).

Guss
  • 12,628
  • Yes I want a different capture per command – Ikaso Jul 25 '17 at 08:53
  • Then read about $PROMPT_COMMAND. you'd probably want to close and reopen your exec every time that gets run – Guss Jul 25 '17 at 09:00
  • If I understand correctly the prompt command is executed right before the prompt is displayed so I will be able to read the last command exit code. Since the command I want to monitor is executed before the PROMPT_COMMAND when will I have a chance to redirect its output? – Ikaso Jul 25 '17 at 10:19
  • I think that is so, checkout the LiquidPrompt application that does something similar (capturing exit code). but I thought you already had that solved. The PROMPT_COMMAND allows you to set up the capture for the next command. – Guss Jul 25 '17 at 10:28