Bash – How to automatically record all your terminal sessions with script utility

bashkonsolescriptingterminal

What I want to achieve is be able to record my terminal sessions to file automatically whenever I use Yakuake/Konsole.

It's easy to achieve if at the start of my session I do:

script -f /home/$USER/bin/shell_logs/$(date +"%d-%b-%y_%H-%M-%S")_shell.log

But I want to run the above automatically whenever I start Yakuake or open a new tab.

Using .bashrc does not work because it creates endless loop as 'script' opens a new session, which in turn reads .bashrc and starts another 'script' and so on.

So presumably I need to script Yakuake/Konsole somehow to run 'script' once as a new tab gets opened. The question is how?

Best Answer

If someone wants to record their terminal sessions automatically--including SSH sessions(!)--using the script utility, here is how.

Add the following line at the end of .bashrc in your home directory, or otherwise /etc/bash.bashrc if you only want to record all users' sessions. We test for shell's parent process not being script and then run script.

For Linux:

test "$(ps -ocommand= -p $PPID | awk '{print $1}')" == 'script' || (script -f $HOME/$(date +"%d-%b-%y_%H-%M-%S")_shell.log)

For BSD and macOS, change script -f to script -F:

test "$(ps -ocommand= -p $PPID | awk '{print $1}')" == 'script' || (script -F $HOME/$(date +"%d-%b-%y_%H-%M-%S")_shell.log)

That's all!

Now when you open a new terminal you'll see:

Script started, file is /home/username/file_name.log

script will write your sessions to a file in your home directory naming them something like 30-Nov-11_00-11-12_shell.log as a result.

More customization:

  • You can append your sessions to one large file rather than creating a new one for every session with script -a /path/to/single_log_file
  • You can adjust where the files are written to by changing the path after script -f (Linux) or script -F (BSD and macOS)

This answer assumes that you have script installed, of course. On Debian-based distributions, script is part of the bsdutils package.

Related Question