Shell Command History – Keeping History Per Working Directory

cd-commandcommand historydirectoryshell

Is there a way to make a modern shell's history feature be scoped to a path?

My working contexts are split up as paths on the file system, and the pattern of shell activity, such as repeatedly issued commands, tends to be distinct to each 'project'. It would be nice if I could scope the history feature to commands issued from the current path (or sub-path).

Best Answer

With zsh, you could do:

mkdir -p ~/.zsh/dirhist

And add to your ~/.zshrc:

HISTSIZE=1000
SAVEHIST=10000
setopt HIST_SAVE_NO_DUPS INC_APPEND_HISTORY
HISTFILE=~/.zsh/dirhist/${PWD//\//@}
chpwd() {
  [[ $PWD = $OLDPWD ]] || fc -Pp ~/.zsh/dirhist/${PWD//\//@}
}

chpwd() is called whenever the current directory changes. There, we reset the history file to something like ~/.zsh/dirhist/@foo@bar when you cd to /foo/bar.

Related Question