Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I gain root permission without leaving vim?

Tags:

linux

vim

sudo

Sometimes when I edit a file which require root permission (e.g. files under /etc), but I forget run vim as sudo.

After edit finished, and type :wq to save and leave, I find I can't, even using !wq, because the file is readonly.

If I leave and re-edit the file, all my work will lost, but if not, I cannot save my edit. So, how can I gain root permission to write without leaving vim?

like image 257
Yongqiang Zhou Avatar asked Jun 06 '12 13:06

Yongqiang Zhou


People also ask

What is Sudo Vim?

sudo. vim : Allows one to edit a file with privileges from an unprivileged session.


2 Answers

To force a save use the following command

:w !sudo tee %

It will prompt you for your password.

like image 51
darryn.ten Avatar answered Sep 28 '22 04:09

darryn.ten


The mentioned trick with tee is nice; if you need this often I'd recommend the SudoEdit plugin, which offers a :SudoWrite command (and even a sudo: protocol handler).

like image 38
Ingo Karkat Avatar answered Sep 28 '22 03:09

Ingo Karkat