Ever open your /etc/hosts file in Vim, make a bunch of edits, only to :wq and get that dreaded read only error? There a few easy ways to sudo write a privileged file in Vim.

When Vim can’t write to a file because it wasn’t opened as sudo, this is the ominous message you’ll see:

E45: 'readonly' option is set (add ! to override)

Ordinarily you might :q! then reopen the file with sudo vim /etc/hosts, entering your password when prompted. But then you’ve lost your changes. If you have tpope’s eunuch.vim plugin, you have an easy option with:

:SudoWrite

This will prompt you for your sudo password and write the file.

If you prefer a native Vim method, you can combine some features of Vim and the Unix tee utility to the same effect:

:w !sudo tee %

This will also prompt you for your sudo password and write the file. But how does it work?

Vim allows you to write the current buffer while piping it through a command with the :w !command syntax. And Vim allows the use of the % character as a substitution for the current buffer’s full file path and name. Therefore, the write is piped through the resulting command sudo tee /etc/hosts. Unix tee utility is used which reads from stdin and writes to stdout along with the specified file. Since tee was invoked with sudo privileges, it can write the to file while Vim cannot.

Arguably, :SudoWrite is easier to remember and eunuch.vim includes a bunch of other useful Unix utilities, so unless you’re a purist, download and install eunuch.vim.