Search code examples
vimvi

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


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?


Solution

  • 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