[Solution] Fix and Recover a corrupt history file in zsh – Linux

If you ever see a message like this upon opening a new shell – “zsh: corrupt history file /root/.zsh_history“. You can easily fix your history file by extracting only the valid strings.

zsh history fix error techhyme

The first step is to move the original .zsh_history file to another renamed file (.zsh_history_backup). It simply move your original file into another.

zsh history fix error techhyme

Next write all printable strings into a new .zsh_history file by typing the following command:

strings .zsh_history_backup > .zsh_history

It seems strings is a nice way to actually get the printable characters in a file. In our case, this means if the .zsh_history was corrupted due to non-printable characters, this will help parse them out. It also means if you ran any commands with non-printable characters, you’ve now lost them from your history as well.

zsh history fix error techhyme

Reload the history by using fc command as shown below:

fc -R .zsh_history

In this case, we are reading from the file and, since no second file was mentioned, putting it back into the same history file. i.e. re-writing history by parsing the same file.

zsh history fix error techhyme

Don’t forget to delete the backup/bad file from the machine that you created in first step.

You may also like:

Related Posts

Leave a Reply