Synchronizing Shell History Between Sessions

Problem

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.

Solution

Use the history command to synchronize your history between sessions manually or automatically.

Discussion

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. ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.