Search code examples
bashpipeexecaudittee

Audit of bash (writing to logfile)


I would like to write the content of my bash shell into a logfile. The logfile should contain STDIN, STDOUT and STDERR.

The most obvious solution to achieve this is to use the script-executable:

script --flush audit.log

But there are two disadvantages:

  1. The logfile contains ugly characters such as: ^M
  2. a new process is created

I am looking for a solution without these disadvantages. And I would like to know where ^M comes from and what it means.

I have not found ^M in output of infocmp.


Solution

  • To start a shell, which writes everything to audit.log you can do this:

    bash -i 2>&1 | tee "audit.log"
    

    With this the audit.log does not contain any more ^M.

    2>&1 redirects STDERR to STDOUT, which is then piped to tee. Tee writes the text, which it receives from the pipe to both STDOUT and file audit.log.

    To avoid that a new process is started you can use the bash built-in command exec:

    exec > >(tee  "audit.log" )                                                                                                                               
    exec 2>&1                                                                                                                                                 
    

    exec allows to redirect STDOUT of current process to a file. >) pipes to tee, which then writes to STDOUT and audit.log.