40

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?

JB.
  • 40,344
  • 12
  • 79
  • 106
Techie
  • 44,706
  • 42
  • 157
  • 243

4 Answers4

106

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

Techie
  • 44,706
  • 42
  • 157
  • 243
  • Related post: [How does the vim “write with sudo” trick work?](http://stackoverflow.com/q/2600783/438329). If you have Tim Pope's [eunuch.vim](https://github.com/tpope/vim-eunuch) then you can do `:SudoWrite` – Peter Rincker Feb 20 '15 at 23:27
  • Also, a good similar alternative with explanations here: https://stackoverflow.com/a/48237738/670521 – DrBeco Oct 24 '19 at 01:51
1

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

press Esc, then type :qa! and press Enter

bdgbdhfh
  • 21
  • 1
1

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

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Hoang Subin
  • 6,610
  • 6
  • 37
  • 56
1
:w /tmp/xyz
:q!

/tmp should always be writeable to erveryone. And then mv or cp the file /tmp/xyz as the correct user to where your original file was

Markus
  • 11
  • 2
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 03 '22 at 18:36