You run more than one bash session at a time and you would like to have a shared history between them.
You’d also like to prevent the last session closed from clobbering the history from any other sessions.
Use the history command to synchronize your history between sessions manually or automatically.
Using default settings, the last shell to gracefully exit will overwrite your history file, so unless it is synchronized with any other shells you had open at the same time, it will clobber their histories.
Manually synchronizing history involves writing an alias to append the current history to the history file, then re-reading anything new in that file into the current shell’s history:
1 2 3 4 5 |
$ history -a $ history -n # OR, 'history sync' alias hs='history -a ; history -n' |
The disadvantage to this approach is that you must manually run the commands in each shell when you want to synchronize your history.
To automate that approach, you could use the $PROMPT_COMMAND variable:
1 |
PROMPT_COMMAND='history -a ; history -n' |
The value of $PROMPT_COMMAND is interpreted as a command to execute each time the default interactive prompt $PS1 is displayed.
The disadvantage to that approach is that it runs those commands every time $PS1 is displayed.
That is very often, and on a heavily loaded or slower system that can cause it significant slowdown in your shell, especially if you have a large history.