Save file after forgetting to open as root / sudo vi [duplicate]

Solution 1:

I think you want something like this:

:w !sudo tee "%"

I first saw it on commandlinefu. The quotes are only necessary if the file path contains spaces.

Solution 2:

i do this occasionally, and if the changes i've made are trivial, i just exit and edit it again as root.

otherwise i save the file to /tmp, and mv/cp it as root to where it really belongs later. and use chown/chgrp/chmod to fix the ownership/perms.

Solution 3:

consider adding this line to your vimrc:

" Remaps :SW to sudo save the current file and tell vim to reload it
command SW execute 'w !sudo tee % >/dev/null' | e! %