Save file as root after editing as non-root

Amir Raminfar picture Amir Raminfar · Dec 19, 2010 · Viewed 10.5k times · Source

Ok so this happens to me all the time. There has to be a better solution. Let's say you do vim /etc/somefile.conf and then you do i but realize you are not sudo and you can't write. So then I lose my changes by doing :q then sudo !! and make my changes again. Is there a better way to do this?

Answer

Joel Spolsky picture Joel Spolsky · Dec 19, 2010

Try

:w !sudo tee "%"

The w ! takes the entire file and pipes it into a shell command. The shell command is sudo tee which runs tee as superuser. % is replaced with the current file name. Quotes needed for files that have either spaces or any other special characters in their names.