Vim Sudo Write Trick
The Trick
You open a file, edit it, and save it only to get the E45 error message that says:
E45: 'readonly' option is set (add ! to override)
You now realise that only root can edit the file. What do you? Start over? No, instead try this:
:w !sudo tee "%"
I learnt this trick recently from the comment section of Tip #975 on the Vim Tips website.
Explanation
How does the :w !sudo tee "%" trick work? Let us look
at the command part-by-part:
-
:w !{cmd}Execute
{cmd}with all lines in buffer as standard input. -
"%"The
%is replaced with the current filename. The quotes around it keeps the filename as a single argument even if it contains whitespace. -
tee {file}The
teecommand is a Unix command (not a Vim command). It copies standard input to standard output and{file}.
More Information
For more information on this command, enter the following commands in Vim:
:help :w_c
:help current-file
:help :_%
Also, enter the following command in shell:
man tee
I hope this was fun!