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.)

  • @jimmij The corrupted file has already been deleted by zsh, so I can't recover by editing the history file.
    – iconoclast
    Dec 28 '18 at 0:44
  • @jimmij And since I have 57698 lines in memory, I'm pretty sure I do have the entire history in memory, based on fc -l 1 | wc -l. What you said maybe true by default, but apparently not with my current Zsh settings.
    – iconoclast
    Dec 28 '18 at 0:46
  • OK, so if you are sure have it all then fc -W should write and fc -A append history to the file. You can pass filename as an argument.
    – jimmij
    Dec 28 '18 at 0:59
  • The only problem (which also occurs with fc -i—or any of the other date options) is that the dates are all wrong before a certain command. I assume that's when the session began, and only commands were loaded into memory, but not dates of previous commands.
    – iconoclast
    Dec 28 '18 at 1:18
  • Does fc -R ~/.zsh_history help?
    – Tuyen Pham
    Jan 15 '19 at 5:00

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.

  • Amazing. This just saved my a$$ after for reasons unknown I lost 30k+ entries from my history file. Fortunately I still had 50+ shell sessions open and most of them had the data in memory. Not sure if it matters, but to avoid potential concurrent access issues, I used bash to replace the ~/.zsh_history file with the file created from the memory dump. Apr 28 '20 at 2:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.