20

Vim Sudo Write Trick

 2 years ago
source link: https://susam.in/maze/vim-sudo-write-trick.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Vim Sudo Write Trick

Vim Sudo Write Trick

By Susam Pal on 25 Aug 2005

The Trick

You open a file, edit it, and save it only to get the E45 error message that says:

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

You now realize that only root can edit the file. What do you? Start over? No, instead try this:

:w !sudo tee "%"

I learnt this trick recently from the comment section of Tip #975 on the Vim Tips website.

Explanation

How does the :w !sudo tee "%" trick work? Let us look at the command part-by-part:

  • :w !{cmd}

    Execute {cmd} with all lines in buffer as standard input.

  • "%"

    The % is replaced with the current filename. The quotes around it keeps the filename as a single argument even if it contains whitespace.

  • tee {file}

    The tee command is a Unix command (not a Vim command). It copies standard input to standard output and {file}.

More Information

For more information on this command, enter the following commands in Vim:

:help :w_c
:help current-file
:help :_%

Also, enter the following command in shell:

man tee

I hope this was fun!


© 2001–2021 Susam Pal


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK