After recovered hstr (BASH History Search Box) (video), I was looking for a way to reduce disk I/O, because of the continuous synchronization on each issued command:

export PROMPT_COMMAND="history -a; history -n; ${PROMPT_COMMAND}"   # mem/file sync

I decided to change to history file to /tmp/.bash_history, which is on a tmpfs filesystem, this way I can be sure no physical disk I/O. The problem was I didn’t sure how to synchronize it, but I think now I have got it.

In .bash_profile or .bash_login:

cp -au $HOME/.bash_history /tmp

-a keeps mode, ownership, and timestamp. -u makes sure no unnecessary copy would be done, only copying when the destination file is older or missing.

Every time a Bash shell is started, the history file shall be copied if that’s very first shell since the boot. It takes care of the preparation of the history file, I’d need to copy it back.

In .bash_logout, very similar, just the other way around:

cp -au /tmp/.bash_history $HOME

Understandably, if computer crashes, the logout script will not be executed, some history could be lost, but I think that wouldn’t be happening often, can’t remember when the last time my computer crashed.

From my personal usage of terminal window, I split my tmux very often, and panes are closed also often, I am not worried about too much, the history file will still be written back frequent, but not as often as doing on every command.

It’s not complicated, all the essential code is only two lines. In my opinion, it’s quite simple, but there might be a more robust way to handle this.