Configure GNU screen so that it stores command histories in files

command-line-interfacegnu-screen

I would like to configure GNU screen such that it stores the command histories of all the different windows in different files.

I know by default GNU screen does not store the command histories (of its different windows) in a file at all (it stores them in memory instead), but it might be possible to tell it to store them in files instead?

The different command history files should have the names <session>.<window>.history, or similar.

Does anyone have an idea how to do that?

(Just to be clear, I want each GNU screen window to write a different file. I like that each window has a different history, and I typically run different types of commands in the different windows.)

Best Answer

Create a script somewhere that looks like this.

~/bin/myshell

#!/bin/bash
HISTFILE=~/.bash_history_w$WINDOW
# HISTFILE=~/.bash_history_w${WINDOW}_s${STY##*.}  # with session name.
export HISTFILE
exec /bin/bash

Adjust your .screenrc with a line like this.

shell ~/bin/myshell

Thanks, but there is a problem: It seems the files don't actually get written until I close a window. In my case though, the windows will always be active and never closed. How can I trigger that the files get written without closing the windows?

You can manually force a write by running the command history -w. I don't believe there is any way to have bash automatically commit the history other then at exit. There appears to be an option to do that in zsh though, search for INC_APPEND_HISTORY.

If you want a log of what was done per session you could use script for that. If you wanted to use script to create per session+window log under script you might adjust myshell like this.

#!/bin/bash
SHELL=/bin/bash  # reset the shell back to bash since screen -s will adjust to to myshell
export SHELL
script -a  -q -f ~/.sessionlog_w${WINDOW}_s${STY##*.}