Write with sudo without leaving Vim
Ever open a privileged file in Vim, make a bunch of edits, only to
:wq and get that dreaded read only error? This commonly happens when editing system files such as your
/etc/hosts file. There are 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 exit Vim with
:q! then reopen the file with
sudo vim /etc/hosts, entering your password when prompted. But then you’ve lost your changes and you’re forced to make your edits again. If you have the eunuch.vim plugin, you’ll have an easy option with the handy
:SudoWrite instead of
:w will prompt you for your sudo password directly in Vim and then will write the file.
But what if you don’t have access to plugins? 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. Combining these means the write is piped through the resulting command
sudo tee /etc/hosts. This uses the Unix
tee utility which reads from stdin and writes to both stdout and the specified file. Since
tee was invoked with sudo privileges, it can write to the file even though Vim cannot.
Here’s a short screencast demonstrating both methods:
:SudoWrite is easier to remember and eunuch.vim includes a bunch of other useful Unix utilities, so unless you’re a purist, or operating off of a remote system without plugins, consider downloading eunuch.vim. Either way, stop exiting Vim and repeating your edits when you forgot to open with
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post?