Vim Error E138: Can't write viminfo file $HOME/.viminfo!

When you run sudo vim you start vim as root. That means that it is the viminfo file in /root that is the problem. You should do rm /root/.viminf*.

To make sure of this, run sudo vim and execute this command: :!echo $HOME. This will show you that your home directory is /root.

I would recommend that you do not run vim as root, but rather use sudoedit. This is a more secure solution as the editor is not running as root. You never know what a plugin might do. Additionally it allows you to use your own settings and plugins in vim and not the ones in roots vimrc. sudoedit is the same as running sudo -e. sudoedit works by making a temporary copy of the file that is owned by the invoking user (you). When you finish editing, the changes are written to the actual file and the temporary file is deleted.

As a general rule of thumb: Do not run things as root if it is not necessary.


I got this error on every exit. I did not use sudo. It explicitly mentioned my user home directory:

E138: Can't write viminfo file /Users/henrik/.viminfo!

Removing ~/.viminfo did not fix the error.

Turns out I had a bunch of viminfo temp files, and removing those fixed the issue:

 ls ~/.viminf*      # If you want to see the files.
 rm -rf ~/.viminf*  # Remove them.

Found this solution here.


I received the same error when trying to :wq a file on a disk that was completely full. If you receive this message, you may wish to check your available disk space.