Posts Tagged ‘zsh’

Making zsh history conditional on command success

Sunday, April 7th, 2019

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:


# called before a history line is saved.  See zshmisc(1).
function zshaddhistory() {
  # Prevent the command from being written to history before it's
  # executed; save it to LASTHIST instead.  Write it to history
  # in precmd.
  LASTHIST=$1
  # 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 && -n $HISTFILE ]] ; then
    print -sr -- ${=${LASTHIST%%$'\n'}}
  fi
}

(more…)