Bash – How to sync terminal session command history in bash

bashcommand historysynchronization

I've
tried to search in ~/.bash_history for my recent commands while in a
terminal session but they just weren't there. I guess this is because I
have multiple terminal sessions open.

Is there a way that I can sync (ie. sync-push or sync-write-out) the
current terminal session's command history into the bash_history file
(without closing the session and losing that environment)?

(It would be remotely similar in idea to how the sync command stores
the file-system modifications on some systems.)

I imagine I could set up bash to preserve multiple session history but
the ability to push the current history buffer would still be useful in
scenarios when you are working on a new machine and you accidentally
forgot to set up bash the way you may would have wanted.

Best Answer

Add this line to .bashrc:

export PROMPT_COMMAND="history -a; history -n"

Open new terminal and check.

Explanation

  • history -a appends new history lines to history file.
  • history -n tells bash to read lines that is not read from history file to current history list of session.
  • PROMPT_COMMAND: contents of this variable is run as regular command before bash show prompt. So every time after you execute a command, history -a; history -n is executed, and your bash history is synced.