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:
:
tellsvi
that you’d like to issue a command.w
tellsvi
to write the current file.!
tellsvi
to expect a shell command to follow.tee
is a shell command to copy from standard input and write to standard output.%
tellsvi
to 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
.