18

I use combination of zsh with oh-my-zsh and iTerm2 for development on Mac. I'm frustrated with the following issue:

  • N tabs opened
  • close the terminal
  • reopen it (with Use system Window Restoration Setting)
  • the history from all previously opened tabs got merged into one for every reopened tab

The question: How to preserve separated history for every reopened tab?

orkenstein
  • 2,810
  • 3
  • 24
  • 45

2 Answers2

27

Per https://github.com/robbyrussell/oh-my-zsh/issues/2537,

Add unsetopt share_history to your .zshrc file.

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
Darren Forsythe
  • 10,712
  • 4
  • 43
  • 54
4

Unless iTerm2 actually just hides a tab on closing and keeps the shell session running in the background (which, according to the iTerm2 website, seems to be an option), it is not possible to completely restore a shell session. In your case It seems like a new shell session is created when restoring a tab, which leads to the history being read form HISTFILE.

If you want to prevent any merging of history, you have to ensure that of the options APPEND_HISTORY, INC_APPEND_HISTORY and SHARE_HISTORY only the first one is set:

setopt noincappendhistory
setopt nosharehistory
setopt appendhistory

This will lead to new entries in the history (i.e. commands run during the session) only being appended to the history file when the shell exits. So when you close a session, the next shell (re-)opened will have lines of the just previously closed shell on the bottom of the history.


Another option could be to have separate history files for each shell session and device your own method of loading a history from these files using the fc builtin. This would at least in part depend on whether it is possible to differentiate between iTerm2 tabs from within a shell session (for example via some environment variable) and whether this holds true when re-opening a tab.

Adaephon
  • 16,929
  • 1
  • 54
  • 71
  • So, looks like there's no easy way? – orkenstein Mar 01 '18 at 18:39
  • i have set up like this but doesnt work: source $ZSH/oh-my-zsh.sh setopt noincappendhistory unsetopt nosharehistory unsetopt appendhistory – Arie May 11 '22 at 05:10
  • @Arie This is equivalent to `setopt sharehistory noincappendhistory noappendhistory`, which would be a valid setting. Aside form that `HISTFILE` needs to be set to a filename in an existing directory and `SAVEHIST` and `HISTSIZE` need to be set to positive integer values. If either `HISTFILE` or `SAVEHIST` are unset, no file will be written or read. If `HISTSIZE` is unset or 0, the history will be written, but will not availabe in the shell. – Adaephon May 11 '22 at 13:22
  • @Adaephon i dont get so what should be written in zshrc to make it work? – Arie May 18 '22 at 21:49