How do you share history between terminals in zsh?

How can it be achieved so that every command that is entered, is visible in every open terminal's history?

When having multiple terminals open, the history isn't shared, i.e. what you entered in one terminals history, doesn't show up in another one. Think of an alternative to Bash's PROMPT_COMMAND="history -a" (which saves the history before the prompt is beeing displayed).


The following options would be applicable:

  • To save every command before it is executed (this is different from bash's history -a solution):

     setopt inc_append_history
    
  • To read the history file everytime history is called upon as well as the functionality from inc_append_history:

     setopt share_history
    

These can be set in your .zshrc file.


⚠️ Either set inc_append_history or share_history but not both. (see comments bellow)

  • When share_history is enabled, it reads and writes to the history file.
  • When inc_append_history is enabled, it only writes to the history file.

Related for bash:

  • Is it possible to make writing to .bash_history immediate?

If you use Robby Russell’s awesome OhMyZSH, it will take care of this and more.

See https://github.com/robbyrussell/oh-my-zsh/blob/master/lib/history.zsh

That includes setopt inc_append_history.