Accueil > Système > Bash: How do I get the command history in a screen session?

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

16/12/2023 Categories: Système Tags: , ,
Print Friendly, PDF & Email

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.

ANSWER:

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}"
Lire aussi:  Bash Shell Loop Over Set of Files
Categories: Système Tags: , ,
Les commentaires sont fermés.