ITerm2 – zsh – keep history of commands when opening a new pane

command linehistoryitermterminalzsh

with zsh on MacOS Catalina, when I split my current window of iTerm2 by opening a new pane, I would like to be able to keep in this new pane the history of commands of previous pane (which is still opened).

Here my current config into ~/.zshrc :

# History
export HISTFILE="$HOME/.zsh_history"
HISTSIZE=10000000
export SAVEHIST=$HISTSIZE
# Avoid duplicates
#setopt HIST_IGNORE_ALL_DUPS
# Remove duplicates in history
function remove_duplicates() {
   echo "$(history 0 | sort -k2 -k1nr | \
   uniq -f1 | sort -n | cut -c8-)" > $HISTFILE
}
remove_duplicates();
setopt inc_append_history

# When the shell exits, append to the history file instead of overwriting it
shopt -s histappend

What is missing or what did I do wrong in this config ?

and Just a question : when I open a new pane, did ~/.zshrc file is executed (I mean sourced like source ~/.zshrc) ?

Best Answer

To share history between sessions, you need to use the SHARE_HISTORY option. Additionally, you will want to append, rather than overwrite your history file.

setopt SHARE_HISTORY
setopt APPEND_HISTORY

Per the ZSH documentation (Chap. 16 - Options) you should also disable INC_APPEND_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). The history lines are also output with timestamps ala EXTENDED_HISTORY (which makes it easier to find the spot where we left off reading the file after it gets re-written).

There's also a few other commands that you may be interested in to deal with your dupes:

  • HIST_NO_STORE - removes the history command from history.
  • HIST_IGNORE_ALL_DUPS - deletes an older version of added commmand
  • HIST_SAVE_NO_DUPS - when saving the history file, older commands that duplicate newer ones aren't saved