5

I connect to a screen session. After doing some stuff I detach it. Then in history | tail I only see screen -r and previous commands and not the commands run in screen session. Basically history shows different things when screen session is running and after it is detached.

How do I make sure that the commands in screen session are appended to bash history?

Config: screen 4.0.3, bash 4.1.2

user13107
  • 5,335

1 Answers1

7

Different shells maintain their own history in memory until it is flushed (written) to history file, which usually happens when you exit the shell, but you can override this as follows:

export PROMPT_COMMAND="history -a; history -c; history -r; ${PROMPT_COMMAND}"

This means every time a new prompt is issued (ie whenever you get through running a command), first the history is appended to the file, then it is cleared from the current shell's memory, then the current shell reloads the history from the file.

This means every shell for your account on the system, whether in screen or multiple windows or whatnot, retains and displays all command history from all other shells.

Put the line in your .bashrc, and you may want to increase your history size by adding this as well:

export HISTSIZE=5000

11/24/2017 EDIT: I just realized there's a problem with my PROMPT_COMMAND: It references itself, which means that if you repeatedly source .bashrc, it will append more and more copies of history -a; history -n to the variable. So, what you want to do instead is something like this:

export PROMPT_COMMAND='history -a; history -n; <whatever other commands you want...>'

Michael Martinez
  • 982
  • 7
  • 12