How do I save a file I opened without sudo permissions?
Answer
:w !sudo tee %
Explanation
The :w !sudo tee % command lets you save a file that requires root permissions, even if you forgot to open Vim with sudo. This saves you from having to close Vim, losing your changes, and reopening the file with elevated privileges.
How it works
:w !commandwrites the current buffer's contents to the standard input ofcommandinstead of directly to the filesudo tee %runsteewith superuser privilegesteereads from standard input and writes to one or more files%is a Vim special variable that expands to the current file's path
So the full command pipes the buffer contents through sudo tee, which writes them to the file with root permissions.
Example
You open /etc/hosts without sudo:
vim /etc/hosts
You make your edits, then try :w and get:
E45: 'readonly' option is set (add ! to override)
Or after :w!:
"Permission denied"
Running :w !sudo tee % prompts you for your sudo password, writes the file, and then displays a message that the file has been modified externally. Press L to reload the file or O to keep your version in the buffer.
Tips
- After running this command, Vim will warn you that the file has changed on disk — press
Lto reload it - You can add a mapping to your vimrc for convenience:
cnoremap w!! w !sudo tee % > /dev/null
- The
> /dev/nullat the end suppresses the output ofteefrom being displayed in the terminal - This trick works on Linux and macOS but not on Windows
- In Neovim, you may need to use
:w !sudo tee % > /dev/nullwith an external terminal prompt or use a plugin that handles sudo writing - Always be cautious when writing system files with root permissions — double-check your changes before saving