How to share bash history between terminal sessions
When working across multiple terminal sessions on a remote Linux instance, it’s convenient to share the same command history everywhere. By default, each bash session (check via tty
) has its own in-memory history. It only writes to ~/.bash_history
when you exit, meaning other sessions won’t see any new commands until you close the first session.
I often find myself working with “headless”/remote Linux instances across multiple terminal sessions. I want to share the command history across terminal sessions for convenience. I treat the history as a “cache” of commands that I’d like to have access to. Usually I can remember portion of a command (like path to a file or argument) and would like to run it again or just tweak it.
My go-to modification that I put in .bash_rc
file is
# append to the history file, don't overwrite it
shopt -s histappend
# Extend the history size
HISTSIZE=10000
HISTFILESIZE=20000
# append, clear, re-load history from history file
PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"
Above means that after each command is executed (or more precisely before next terminal prompt after command is executed):
- in terminal X history immediately written to the history file (which makes it visible for new terminal sessions),
- in-memory history contents are cleared,
- the history file is read.
If a terminal Y added commands they will now be available in terminal X. Terminal Y will then re-read the history contents after you execute the next command or hit
enter
button.
I’m aware that this handling of terminal history may not be for everyone but it makes me much more productive when I’m juggling multiple terminals and mostly care about running similar or same commands over long period of time.