56

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

MJB
  • 1,804
  • See also related and advanced Q&A: http://superuser.com/questions/446594/separate-up-arrow-lookback-for-local-and-global-zsh-history/691603#691603 – lumbric Dec 22 '13 at 18:27

2 Answers2

66

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 every time 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 below)

  • 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?

Pablo Bianchi
  • 15,657
MJB
  • 1,804
  • 7
    "SHARE_HISTORY: This option both imports new commands from the history file, and also causes your typed commands to be appended to the history file (the latter is like specifying INC_APPEND_HISTORY, which should be turned off if this option is in effect)." (From manual emphasis added) i.e. just the INC_APPEND_HISTORY option will do what you want. – artfulrobot Oct 20 '14 at 10:30
  • 4
    Actually, just the SHARE_HISTORY option alone will do what you want. The phrase "which should be turned off if this option is in effect" translates to "[INC_APPEND_HISTORY] should be turned off if [SHARE_HISTORY] option is in effect". I've tested this on zsh 5.1.1 on Ubuntu Xenial. – Linus Arver Feb 02 '17 at 00:33
  • 1
    @opert is correct: setopt share_history is what will accomplish the desired result. @MJB would you be willing to edit your answer to remove the mention of setopt inc_append_history? It obscures the actual answer. – bonh Feb 22 '17 at 16:40
  • Names are case insensitive and underscores are ignored so if you setopt | grep hist will get incappendhistory and sharehistory. – Pablo Bianchi Oct 05 '17 at 21:16
  • 1
    Just to clarify. You write command in shell 1, then switch to shell 2 and press enter. You will see that command as last only in case of share_history, but not inc_append_history. – seeker_of_bacon Jan 03 '20 at 17:52
8

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.

bfirsh
  • 3