How to write file content with sudo in Vim?
Posted on In QA, TutorialVim opens file even if the user does bot have write permission to the file. But after revision, how to write file content with sudo in Vim if Vim reports no permission to write the file.
Use this command inside of vim
to write to the file with sudo
:
:w !sudo tee %
Here, !
and %
are 2 special vim
variables.
!
pipes the contents of the current buffer to another command.
%
means “the current file”
sudo tee FILE
is a common trick to write to a file as root by sudo
. Note that in a wrong command sudo cat >FILE
for such purpose, the user that tries to write to the FILE is the current user instead of the root
.
Some other common tricks for sudo
also work here, such as
:w !sudo sh -c "cat > %"