Saving a read-only file in vi.
Oops
Let’s say that you’ve just finished a long edit of a read-only config file as a regular user. You forgot to open the file with elevated privileges. What do you do? Thankfully, vi allows users to run UNIX commands without having to exit the program:
:w !sudo tee %
Here’s a quick breakdown of the above command:
:tellsvithat you’d like to issue a command.wtellsvito write the current file.!tellsvito expect a shell command to follow.teeis a shell command to copy from standard input and write to standard output.%tellsvito use the current file name.
As an aside, you may also be interested to note that you can open a shell prompt from within vi by running :sh. vi will use whatever is returned by echo $SHELL.