On Ubuntu 24 `history` is different before and after `screen`, how to make it common?
May 13, 9:23am

On Ubuntu 24.04 (and most Linux systems), the history command in Bash reads from the ~/.bash_history file, but only when the session starts. If you use screen (or tmux), each new shell inside screen starts a new session, which means it loads the history from ~/.bash_history at that moment—but it does not automatically sync changes back to the file when the session ends.

Why is history different before and after screen?

  • Before screen: Your main terminal session has its own in-memory history, which is written to ~/.bash_history only when the session exits cleanly.
  • After screen: Each shell inside screen has its own in-memory history. When you exit screen, the history from those shells is not appended to ~/.bash_history unless explicitly configured.

How to Make History Common

1. Append History Immediately

Add these lines to your ~/.bashrc to ensure history is appended immediately after each command:

bash
shopt -s histappend
PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"
  • histappend: Appends to ~/.bash_history instead of overwriting.
  • history -a: Appends the current session's history to ~/.bash_history.
  • history -c: Clears the in-memory history (to avoid duplicates).
  • history -r: Reloads the history from ~/.bash_history.

2. Set a Large History Size

Also in ~/.bashrc, increase the history size to avoid losing commands:

bash
HISTSIZE=10000
HISTFILESIZE=20000

3. Reload History in All Sessions

If you have multiple terminals or screen sessions open, run:

bash
history -a; history -r

This forces all sessions to sync with ~/.bash_history.

4. For screen Specifically

If you want screen to share history with your main shell, ensure that:

  • All shells (inside and outside screen) use the same ~/.bash_history.
  • The PROMPT_COMMAND trick above is applied to all shells.

5. Alternative: Use tmux

If you switch to tmux, it handles history sharing more gracefully by default, as all panes/windows share the same environment.


Verify It Works

  1. Open a terminal and run a few commands.
  2. Open screen and run a few more commands.
  3. Exit screen and check history in your main terminal—it should now include commands from both sessions.

May 13, 9:23am

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Le Chat can make mistakes. Check answers. Learn more