How to fix and recover a “corrupt history file” in ZSH
Table of contents⌗
Introduction⌗
Once in a while, you will come across an error like “corrupt history file” when using the ZSH shell after doing something like a hard shutdown of your computer.
zsh: corrupt history file /home/username/.zsh_history
This error can easily be fixed by re-writing the history file.
In this article, the history file is named .zsh_history
which is always the case but if the error shows a different file name, substitute that in.
System requirements⌗
strings
package. You can check your distro if it has this already installed or install it usingbinutils
.
Step-by-step fixing of the file⌗
This is how you fix it:
1. Locate the file and rename it⌗
Typically, the file will be located in the home directory. You need to rename it so that in the end, we have the original file name available.
cd ~
mv .zsh_history .zsh_history_bad
2. Get all the printable characters⌗
strings .zsh_history_bad > .zsh_history
The strings
command helps us to get the printable characters in the file.
The downside to this is that if you had non-printable characters in the commands you ran in ZSH
before, they all get lost. For our fix, we are writing all printable strings into a new .zsh_history
file.
3. Re-write the file⌗
The fc
command controls the interactive history mechanism. We are reading from the .zsh_history
file and, since no second file was mentioned, we put it back into the same history file.
fc -R .zsh_history
4. Clean up⌗
Remove the .zsh_history_bad
file.
rm -rf .zsh_history_bad
Conclusion⌗
Whenever you are using the ZSH shell and you power down your computer or Virtual Machine, the shell is still written into the history file. In the event this write is interrupted and corrupted, you can easily get the file back using the fixing steps explained above.
In summary
cd ~
mv .zsh_history .zsh_history_bad
strings .zsh_history_bad .zsh_history
fc -R .zsh_history
rm -rf .zsh_history_bad