Zsh – How to Clear History in Zsh

command historyzsh

I'm looking for the zsh equivalent of the bash command history -c, in other words, clear the history for the current session. In zsh history -c returns 1 with an error message history: bad option: -c.

Just to clarify, I'm not looking for a way to delete the contents of $HISTFILE, I just want a command to reset the history to the same state it was in when I opened the terminal. Deleting the contents of $HISTFILE does the opposite of what I want: it deletes the history I want to preserve and preserves the history I want to delete (since current session's history would get appended to it, regardless if its contents was previously erased).

There is a workaround I use for now, but it's obviously less than ideal: in the current session I set HISTFILE=/dev/null and just close and reopen the terminal. This causes the history of the closed session not be appended to $HISTFILE. However, I'd really like something like history -c from bash, which is much more elegant than having to close and restart the terminal.

Best Answer

To get an empty history, temporarily set HISTSIZE to zero.

function erase_history { local HISTSIZE=0; }
erase_history

If you want to erase the new history from this shell instance but keep the old history that was loaded initially, empty the history as above then reload the saved history fc -R afterwards.

If you don't want the erase_history call to be recorded in the history, you can filter it out in the zshaddhistory hook.

function zshaddhistory_erase_history {
  [[ $1 != [[:space:]]#erase_history[[:space:]]# ]]
}
zshaddhistory_functions+=(zshaddhistory_erase_history)

Deleting one specific history element (history -d NUM in bash) is another matter. I don't think there's a way other than:

  1. Save the history: fc -AI to append to the history file, or fc -WI to overwrite the history file, depending on your history sharing preferences.
  2. Edit the history file ($HISTFILE).
  3. Reload the history file: fc -R.