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.
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. Using the shell option shown in Setting Shell History Options, to append rather than overwrite the history file helps, but keeping your history in sync across sessions may offer additional benefits.
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:
$ 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:
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.
help history
18.191.147.77