If you open a file that you don't have permission to write to in vim, then decide you need to change it, you can write your changes without exiting vim by doing :w !sudo tee %
I don't understand how this can work. Can you please dissect this?
I understand the :w
part, it writes the current buffer to disk, assuming there already is a file name associated with it, right?
I also understand the !
which executes the sudo tee
command and %
represents the current buffer content right?
But still don't understand how this works.
How does `:w !sudo tee %` work
sudoteevim
Best Answer
The structure
:w !cmd
means "write the current buffer piped through command". So you can do, for example:w !cat
and it will pipe the buffer throughcat
.Now
%
is the filename associated with the bufferSo
:w !sudo tee %
will pipe the contents of the buffer throughsudo tee FILENAME
. This effectively writes the contents of the buffer out to the file.