vim Getting started with vim Saving a read-only file edited in Vim


Example

Sometimes, we may open a file which we do not have permission to write in Vim without using sudo.

Use this command to save a read-only file edited in Vim.

:w !sudo tee > /dev/null %

Which you could map to :w!! in your .vimrc:

cmap w!! w !sudo tee > /dev/null %

You will be presented a prompt as shown in the image.

Press ENTER or type command to continue. [O]K, (L)oad File:.

Press O and the file will be saved. It remains open in vi/vim for more editing or reading and you can exit normally by typing :q! since the file is still open as read-only.

Command Explanation

:w ............................ isn't modifying your file in this case, 
   ............................ but sends the current buffer contents to 
   ............................ a substituted shell command
   !sudo ...................... call the shell 'sudo' command
         tee .................. the output of the vi/vim write command is redirected 
                                using the 'tee' command
             > /dev/null ...... throws away the standard output, since we don't need 
                                to pass it to other commands
                         % .... expands to the path of the current file

Sources: