search

Home  >  Q&A  >  body text

How to switch to another user to continue editing while retaining the currently edited content in vim

This is a frequently encountered situation. For example, we often need to connect to the server and use vim to modify the configuration file. Most configuration file modifications require sudo permissions, but when reading unnecessary. Therefore, many times we use the current system account to modify files for a long time, only to find out at the end :wq that we do not have write permission. In the past, I used sudo vim to re-edit after exiting, but this method is too troublesome. Is there any other way to retain the currently edited content when switching users?

PHPzPHPz2773 days ago805

reply all(3)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-16 16:45:06

    :w !sudo tee %

    Reference: http://vim.wikia.com/wiki/Su-write

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-16 16:45:06

    Execute the following in vim to save the file contents without switching users. .

    :%!sudo bash -c "cat > '%'"

    p.s. If there are no special symbols such as spaces in the file name, the quotation marks around the last % can be omitted.

    reply
    0
  • 黄舟

    黄舟2017-05-16 16:45:06

    Save to another file, then exit, overwriting the file

    reply
    0
  • Cancelreply