GNU screen loses (parts of) command histories

Solution 1:

You'd be better off using Bash's history than screen's. Screen keeps a scrollback buffer (probably in-memory rather than in a file). When you recall commands using Ctrl-a { it's actually digging through everything that appeared on the screen that's still in the buffer that looks like it follows a prompt character. There's not really a command history. You can increase the size of the scrollback buffer using screen -h num or the defscrollback num or scrollback num screen commands, by the way.

You can use warren's suggestion to keep your Bash history up to date. And/or you can use one of my logging functions found here that can save your IP address or screen session ID along with date, time, current working directory and actual command. I use this all the time myself. You may have to set the variable $hcmntextra, which is used by my functions, to include $STY so the screen session name is logged, too.

Solution 2:

I asked a similar question on SU a bit ago: https://superuser.com/questions/37576/can-history-files-be-unified-in-

To quote the accepted answer:


here are two things you need to do:

Insert the command shopt -s histappend in your .bashrc. This will append to the history file instead of overwriting it.
Also in your .bashrc, insert PROMPT_COMMAND="$PROMPT_COMMAND;history -a; history -n" and the history file will be re-written and re-read each time bash shows the prompt.


See also the history man pages.

Solution 3:

My preferred solution to this problem is a variation of one of the previous answers.

I like to have a separate file stored for each screen session/window combination and each file is appended each time its corresponding prompt is shown:

if [[ "$STY" = "" ]]; then STY="none"; fi
if [[ "$WINDOW" = "" ]]; then WINDOW="none"; fi
export HISTFILE=~/.bash_history.$STY.$WINDOW;


PROMPT_COMMAND="$PROMPT_COMMAND; history -a"

This creates the following history files:

.bash_history.none.none
.bash_history.2756.pts-9.linux.0
.bash_history.2756.pts-9.linux.1
.bash_history.2881.pts-9.linux.0

If you want window {x} to always use its own history file but use the same file regardless of the screen session, you can merely leave out the STY variables:

if [[ "$WINDOW" = "" ]]; then WINDOW="none"; fi
export HISTFILE=~/.bash_history.$WINDOW;


PROMPT_COMMAND="$PROMPT_COMMAND; history -a"

This would create the following history files:

.bash_history.none
.bash_history.0
.bash_history.1
.bash_history.2