Home » Questions » Computers [ Ask a new question ]

Getting root permissions on a file inside of vi? [closed]

Getting root permissions on a file inside of vi? [closed]

"Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.












Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 2 years ago.





Improve this question





Often while editing config files, I'll open one with vi and then when I go to save it realize that I didn't type

sudo vi filename

Is there any way to give vi sudo privileges to save the file? I seem to recall seeing something about this while looking up some stuff about vi a while ago, but now I can't find it."

Asked by: Guest | Views: 322
Total answers/comments: 2
Guest [Entry]

"% is replaced with the current file name, thus you can use:

:w !sudo tee %

(vim will detect that the file has been changed and ask whether you want to it to be reloaded. Say yes by choosing [L] rather than OK.)

As a shortcut, you can define your own command. Put the following in your .vimrc:

command W w !sudo tee % >/dev/null

With the above you can type :W<Enter> to save the file. Since I wrote this, I have found a nicer way (in my opinion) to do this:

cmap w!! w !sudo tee >/dev/null %

This way you can type :w!! and it will be expanded to the full command line, leaving the cursor at the end, so you can replace the % with a file name of your own, if you like."
Guest [Entry]

"In general, you can't change the effective user id of the vi process, but you can do this:

:w !sudo tee myfile"