If you know ahead of time that you need to be editing a file as root, using the commands sudoedit <file>
or sudo -e <file>
will get you setup in a special environment for doing so with your usual editor preferences. A copy of the file is made and your editor is launched to edit it (as your user). When you exit the file is copied back to it's original location as root.
That is the safest and recommended way, but in the event that a) you don't realize ahead of time you will need to write as root or b) want to edit and save incremental changes in-place, you will need something else. To this end the solution using sudo tee
proposed by smpl is definitely on the right track, but there are some minor improvements that can be made to handle edge cases. Notably the difference in handling the sudo password prompt in a GUI vs. console interfaces is worth some attention.
An easier way to set this up is to use the vim-eunuch plugin. It has this particular issue and a few other handy things rolled up into a handy package. Usage is as simple as calling :SudoWrite
. I even use a slightly handier access mapping:
cmap w!! call SudoWrite()
That should get you the ability to write a any file as root using :w!!
.
sudo vim file
is better written assudo -e file
(provided that you set the environment variableEDITOR=vim
). – lcd047 Jun 11 '15 at 4:31