[vim] with sudo permission to save vim open readonly file
The following command is to be stated in this article:
: W! sudo tee% >/dev/null
In the Linux configuration, you will change to read-only files, such as/etc/profile
$ ls-al/etc/profile
-rw-r–r–1 root root 1139 Mar 17:30/etc/profile
Use VIM to open the file/etc/profile modified, save will be wrong:
: W
E45: ' readonly ' option is set (add! To override)
Follow the prompts to add an exclamation mark to the end of the command, then execute again, or make an error:
: w!
"/etc/profile" E212:can ' t open file for writing
Use the following command to resolve. At this point, vim will have two interactions,
One, enter the password:
: W! sudo tee% >/dev/null
[sudo] password for user:
Second, the warning file has been modified and a menu of options is displayed.
Press the L key here to re-load the file into the buffer.
Press ENTER or type command to continue
W12:Warning:File "/etc/profile" has changed and the buffer were changed in Vim as well
See ': Help W12 ' for more info.
O K, (L) oad File:
How the command works:
Consult the VIM documentation (input: HELP:W), which will mention: Write! {cmd}.
: [Range]w[rite] [++opt]! {cmd}
Execute {cmd} with [Range] lines as standard input
(Note the space in front of the '! '). {cmd} is
Executed like with ":! {cmd} ", any '!" was replaced with
The previous command:!.
The command passes the contents of the buffer as standard input to the specified {cmd}, and {cmd} can be any external command or program. This uses the external command tee to run save with sudo privileges. The symbol% in the command is the name of a read-only register in Vim, which always holds the file path of the currently edited file, which expands to the full path of the current file/etc/profile. The contents of the buffer are then treated as standard input, overwriting the contents of the edited file. Vim detects that the file has been modified by an external program and will be prompted to select it. However, the contents of the files and buffers here are consistent.
This command is absurd, but often used. In this case, a deeper understanding is also helpful in remembering this command.