Zsh – How to Exclude Specific Commands from Saving into History

command historyzsh

I want to exclude some specific commands from saving into zsh history.

for e.g: exclude mpv/mpc commands from saving into zsh history regardless of setting HIST_IGNORE_SPACE or not.

I found an answer here but it does not work when I test it.

Best Answer

Consider a hook function to check the command before adding to the history file:

zshaddhistory() {
  case ${1%% *} in
    (mpv|mpc) return 1;;
  esac
  return 0;
}

Quoting the section of the man page (man zshmisc, under "Hook Functions"):

If any of the hook functions returns status 1 (or any non-zero value other than 2, though this is not guaranteed for future versions of the shell) the history line will not be saved, although it lingers in the history until the next line is executed, allowing you to reuse or edit it immediately.

If any of the hook functions returns status 2 the history line will be saved on the internal history list, but not written to the history file. In case of a conflict, the first non-zero status value is taken.

Related Question