Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the command history in a screen session using Bash?

Tags:

If I start a screen session with screen -dmS name, how would I access the command history of that screen session with a script?

Using the , the last executed command appears, even in screen.

like image 893
hexacyanide Avatar asked Feb 16 '13 20:02

hexacyanide


People also ask

How do I find previous commands in bash?

You can search command from the history by pressing Ctrl+R. When these keys are pressed then a search option will appear. The command will search from the history based on the keypress by the user.

How do I view bash history?

The command is simply called history, but can also be accessed by looking at your . bash_history in your home folder. By default, the history command will show you the last five hundred commands you have entered.

How do I view screen history in Linux?

Ctrl + A , followed by Esc.


1 Answers

I use the default bash shell on my system and so might not work with other shells.

this is what I have in my ~/.screenrc file so that each new screen window gets its own command history:

Default Screen Windows With Own Command History

To open a set of default screen windows, each with their own command history file, you could add the following to the ~/.screenrc file:

screen -t "window 0" 0 bash -ic 'HISTFILE=~/.bash_history.${WINDOW} bash' screen -t "window 1" 1 bash -ic 'HISTFILE=~/.bash_history.${WINDOW} bash' screen -t "window 2" bash -ic 'HISTFILE=~/.bash_history.${WINDOW} bash' 

Ensure New Windows Get Their Own Command History

The default screen settings mean that you create a new window using Ctrl+a c or Ctrl+a Ctrl+c. However, with just the above in your ~/.screenrc file, these will use the default ~/.bash_history file. To fix this, we will overwrite the key bindings for creating new windows. Add this to your ~/.screenrc file:

bind c screen bash -ic 'HISTFILE=~/.bash_history.${WINDOW} bash' bind ^C screen bash -ic 'HISTFILE=~/.bash_history.${WINDOW} bash' 

Now whenever you create a new screen window, it's actually launching a bash shell, setting the HISTFILE environmental variable to something that includes the current screen window's number ($WINDOW).

Command history files will be shared between screen sessions with the same window numbers.

Write Commands to $HISTFILE on Execution

As is normal bash behavior, the history is only written to the $HISTFILE file by upon exiting the shell/screen window. However, if you want commands to be written to the history files after the command is executed, and thus available immediately to other screen sessions with the same window number, you could add something like this to your ~/.bashrc file:

export PROMPT_COMMAND="history -a; history -c; history -r; ${PROMPT_COMMAND}" 
like image 95
Nathan S. Watson-Haigh Avatar answered Sep 26 '22 03:09

Nathan S. Watson-Haigh