4

Possible Duplicate:
How does the vim “write with sudo” trick work?

Many times I have found myself in a condition where I end up editing file in vi editor for which I don't have permission. So then we have to copy the content in some other file and copy it back to original file by changing the permissions. But I have found one solution through searching web that we can give command :w !sudo tee % and there is no need for copying back and forth. Can anybody explain how this is working !!

Community
  • 1
  • 1
niting112
  • 2,498
  • 2
  • 16
  • 18

2 Answers2

6

Let's see...

:w !{cmd}

executes {cmd}, feeding the current buffer into its standard input.

Here, {cmd} is sudo tee %. This executes tee {filename} as root, where {filename} is the name of the file you're editing. The command writes its standard input (i.e. the contents of the vim buffer) into the file, as root.

Neat trick, BTW.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

You're writing the file to the STDIN of the command:

sudo tee %

sudo escalates your permissions and tee writes STDIN to the file (% is replaced by the current filename by vim before executing the command)

speshak
  • 2,457
  • 3
  • 27
  • 34