How to recover a corrupted Zsh history file from memory

command historyzsh

For reasons that partially escape me (and are outside the scope of this question), my Zsh history file became corrupt. I have several sessions open that have the history in memory. Is there a way to recover the history file (in its correct format) from what's in memory?

While the output of the history or fc commands looks like this (by default, at least)

57694  type -a ssh-keygen
57695  ssh -v localhost

while the file is in a format like

: 1545938685:133;vim ~/.zshrc
: 1545938820:0;exit

(Obviously these are not the same entries—I just give them to display the format, and therefore the problem I'm facing.)

Is there any way to get fc to display all the data that I would need to recreate the history file as it was before it became corrupted?

(If this is not possible, I can recover most of it from a backup drive, of course, but I would rather recover all of it, and it would be useful to know how to do this in the future.)

Best Answer

Digging into ZSHBUILTINS(1)'s man page I found that:

fc -W .zsh_history_from_ram

writes to a file the history in the exact same format it is saved by zsh in ~/.zsh_history. This will work as long as you have a shell session that still has the history in memory.

Related Question