Making zsh history conditional on command success

So I thought it would be useful to exclude failed commands from my on-disk zsh history, while still having them available in the in-memory history until the current shell exits. This means that when you’re trying to find the one magic incantation that works of some esoteric command that you haven’t used for years, you can just search for it in your history without fear of repeating old mistakes.

From my .zshrc:


# Prevent the command from being written to history before it's
# executed; save it to LASTHIST instead.  Write it to history
# in precmd.
#
# called before a history line is saved.  See zshmisc(1).
function zshaddhistory() {
  # Remove line continuations since otherwise a "\" will eventually
  # get written to history with no newline.
  LASTHIST=${1//\\$'\n'/}
  # Return value 2: "... the history line will be saved on the internal
  # history list, but not written to the history file".
  return 2
}

# zsh hook called before the prompt is printed.  See zshmisc(1).
function precmd() {
  # Write the last command if successful, using the history buffered by
  # zshaddhistory().
  if [[ $? == 0 && -n ${LASTHIST//[[:space:]\n]/} && -n $HISTFILE ]] ; then
    print -sr -- ${=${LASTHIST%%'\n'}}
  fi
}

Continue reading “Making zsh history conditional on command success”