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?


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

    链接地址: http://www.djcxy.com/p/49576.html

    上一篇: Unix:混淆使用Tee

    下一篇: 如何将我在vim中打开的文件保存为错误的用户?