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.
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.
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.
Ctrl + A , followed by Esc.
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:
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'
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.
$HISTFILE
on ExecutionAs 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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With