How does `:w !sudo tee %` work

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 through cat.

Now % is the filename associated with the buffer

So :w !sudo tee % will pipe the contents of the buffer through sudo tee FILENAME. This effectively writes the contents of the buffer out to the file.


% represents the current buffer's filename, not its contents.

so :w !sudo tee % means pipe the current buffer to sudo tee [currentfilename].

tee is being run as root, so has write access to save its stdin to the file.

See also https://stackoverflow.com/questions/2600783/how-does-the-vim-write-with-sudo-trick-work


Not quite right!

!command runs command as a filter command, which get text from stdin, do something and output to stdout.

By using w, you pushed file content to stdin of sudo tee %. % is special register in vim, which holds the name of current file.

So you got sudo tee FILENAME, which will push tee stdin - file content - to current file.

Tags:

Vim

Sudo

Tee