vimtricks.wiki Concise Vim tricks, one at a time.

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 !command writes the current buffer's contents to the standard input of command instead of directly to the file
  • sudo tee % runs tee with superuser privileges
  • tee reads 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 L to reload it
  • You can add a mapping to your vimrc for convenience:
cnoremap w!! w !sudo tee % > /dev/null
  • The > /dev/null at the end suppresses the output of tee from 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/null with 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

Next

How do I edit multiple lines at once using multiple cursors in Vim?