Save a file from vim with root permissions

Have you ever run into this situation? You open a system configuration file in vim, make your changes, and now vim is failing to save them because you forgot to open the file as root: Can't open file for writing: permission denied.

But don’t worry, you don’t have to start over again! You can do the sudo right from your vim command line. Even though :w won’t work, this following command will:

:w !sudo tee %

After saving your file this way, you can exit vim via :q! against its warnings that it issues because it’s not aware that you did manage to save your file against all odds.

Now, what does this seemingly meaningless sequence of arguments do?

The key to this emergency save is that a file name isn’t the only possible argument to the :w write command. You can alternatively provide a shell command, prefixed with an exclamation mark. This command will then receive the buffer contents from vim via STDIN. Since we need root permissions, sudo is our command of choice in this case.

But sudo needs to run a command now, too. What command can we use to write what comes from STDIN to a file? cat comes to mind, but that would require an output redirection. And those are tricky with sudo because not sudo will set up that redirection but the shell — before it executes sudo. Which means that it won’t work as intended.

That’s why we use tee here. We can pass it the name of the file into which it will write as an argument, and we do exactly that. Well, actually vim does that via its % placeholder that it will replace with the path to the file in the active buffer.

In summary, the sequence :w !sudo tee % passes the content of the current buffer via STDIN to sudo, which in turn passes them on to tee. Finally, tee will write the buffer content to the file that’s currently open in vim, and it’ll succeed because it’s running with root permissions.

I love vim (and its derivatives) because it is such a treasure trove of features, many of which can come in clutch just when you need them.

So much to learn!

Find easily digestible pieces of DevOps experience in your inbox on Monday morning. Join 121 DevOps people who are already getting my News From the Server Room every week!

We keep your data private and share your data only with third parties that make this service possible. Read our full Privacy Policy.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *