How to remove the last command (or current command for bonus) from zsh history

command historyzsh

Sure there's a super simple smart way to do this, but since history in zshell seems to be aliased to fc, there's no way to use the tricks mentioned in How to remove a single line from history?.

Any pointers on how to do this? My use case would be to remove the last issued command from history so it stops autocompleting (mostly when you've mistyped something and it keeps showing up).

I know I can get the last issued command by doing

history | tail -n 1, but history -d doesn't work and I can't find proper documentation for zsh.

Best Answer

Zsh doesn't offer a real history edition facility. The command history is basically read-only. All you can do is replace it wholesale.

To edit the command line history:

  1. Save it to a file: fc -W
  2. Edit the file
  3. Load the history from the file: fc -R

You can choose the file name by setting HISTFILE.

Untested code:

remove_last_history_entry () {
  setopt local_options extended_history no_hist_save_no_dups err_return

  local HISTFILE=~/.zsh_history_tmp_$$ SAVEHIST=$HISTSIZE
  fc -W
  ed -s $HISTFILE <<EOF >/dev/null
d
w
q
EOF
  fc -R
}
Related Question