Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save a file I opened in vim as the wrong user?

Tags:

vim

vi

This happens to me all the time. I login as a normal user and start editing a file using vim. After editing is done, when I try to save the file, I don't have enough permission to save the file. I have to close the file, login as root and start editing again. Below is the given error in vim:

E45: 'readonly' option is set (add ! to override)

Or in plain vi:

File is read only

Is there a way to save without leaving the editor?

like image 894
Techie Avatar asked Feb 20 '15 18:02

Techie


People also ask

How do I save a vim file with a different name?

It's time to open up the command mode of Vim by pressing the “:” key. Now, press the “w” key from the keyword followed by the space key and the new name of a file. Tap “Enter” to execute this command on Vim. Now, the exact copy of the same file has been created in the home folder with a new filename.

How do I save changes after 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. To the non-vi initiated, write means save, and quit means exit vi.


3 Answers

Try the below command

:w !sudo tee % 

Explanation

  • :w – write
  • !sudo – call shell sudo command
  • tee – the output of write (:w) command is redirected using tee
  • % – current file name

More info

like image 178
Techie Avatar answered Oct 07 '22 19:10

Techie


E45: 'readonly' option is set (add ! to override)

press Esc, then type :qa! and press Enter

like image 27
bdgbdhfh Avatar answered Oct 07 '22 19:10

bdgbdhfh


Just simply type your command with sudo like sudo vi filename.txt.

Then, hit i, edit what you want to change and hit Esc. Then :wq

like image 28
Tran Son Hoang Avatar answered Oct 07 '22 19:10

Tran Son Hoang