Vim: Save file in read-only mode without restart your work

Open a file as normal, forgetting to use “sudo”, and therefore viewing a read-only file.

Then mistakenly try to edit the read-only file in the traditional manner.

:w !sudo tee%

At this point we will be presented with the content of the file and a prompt to press ENTER or type another command.

To simply save the file and move on we just press ENTER, and then press the letter “O” (oh).

(NOTE: “L” seems to do pretty much the same thing.)

The file will be saved but remains open in vi/vim for more editing or reading.

We can now exit normally by typing “:q!” since the file is still open as “read-only”.

What the command does:
:w = Write a file.
!sudo = Call shell sudo command.
tee = The output of the vi/vim write command is redirected using tee.
% = Triggers the use of the current filename.
Simply put, the ‘tee’ command is run as sudo and follows the vi/vim command on the current filename given.