Tip 46Save a File as the Super User

Running Vim as the super user isn’t normal, but sometimes we have to save changes to a file that requires sudo permission. We can do so without restarting Vim by delegating the task to a shell process and running that with sudo.

This tip may not work in GVim and certainly won’t work on Windows. It does work on Unix systems when you run Vim inside a terminal, which is a common enough scenario to make this tip worthy of inclusion.

Let’s use the /etc/hosts file to demonstrate. The file is owned by root, but we’re logged in with username “drew,” so we have permission only to read this file:

=> $ ls -al /etc/ | grep hosts
<= -rw-r--r-- 1 root wheel 634 6 Apr 15:59 hosts
=> $ whoami
<= drew

We’ll open ...

Get Practical Vim, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.