Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save file as root after editing as non-root

Tags:

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?

like image 525
Amir Raminfar Avatar asked Dec 19 '10 17:12

Amir Raminfar


People also ask

How do I save a sudo edit?

By typing Ctrl+X nano exits and if your file needs change you will be prompted to save the changes in which case to save you should press Y and then enter to save changes in the same file you open. If you are not using any gui and you just want to leave the shell the command is Ctrl+D.

How do I save after sudo vi?

To save a file, you must first be in Command mode. Press Esc to enter Command mode, and then type :wq to write and quit the file. The other, quicker option is to use the keyboard shortcut ZZ to write and quit.


2 Answers

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.

like image 127
Joel Spolsky Avatar answered Sep 17 '22 12:09

Joel Spolsky


Depending on the extent of your changes, it might be faster to save (:w) your file with a different name, and then use sudo and cat to overwrite the content of the original file:

sudo sh -c 'cat changed > file'

Note that both cp and mv will replace the original file and its attributes (ownership, permissions, ACLs) will be lost. Do not use them unless you know how to fix the permissions afterwards.

like image 36
thkala Avatar answered Sep 18 '22 12:09

thkala