Saving a read-only file edited in vi / vim

We’ve all done it…opened a file using vi or vim to inspect the contents, and realize we need to alter it.  Of course we totally ignored the message informing we didn’t have permission to edit, so we’re only allowed to view it as “read-only”.  Then after we find the troublesome spot we hit “i” and happily edit the place needing changed, only to “face-palm” when we realize we cannot save the wonderful edit we just made.

In the past I handled this one of three ways: I either copied and pasted the change after reopening the file using sudo, or I reopened and retyped everything once again, or I save the file as a temp file and then rename it using sudo.  Very stupid, stressful and time consuming.

However, now I know a better way.  Using a combination of ‘tee’ and ‘sudo’ commands I can now save the read-only file rather than jumping through the hoops in the previous paragraph.  Here is how:

Open a file as normal, forgetting to use “sudo”, and therefore viewing a read-only file.

Then mistakenly try to edit the read-only file in the traditional manner.

But when we try to save using ‘:w!’, SHIFT+ZZ, or :qw!, or whatever combination we normally fail with as an alternative.  Here is sample output of what we see:

At this point is where the new magic can happen. Instead of the normal “face-palm” we do not “ENTER” and move on. We can enter a new command and successfully save the file after entering the sudo password:

At this point we will be presented with the content of the file and a prompt to press ENTER or type another command. To simply save the file and move on we just press ENTER, and then press the letter “O” (oh). (NOTE: “L” seems to do pretty much the same thing.)  The file will be saved but remains open in vi/vim for more editing or reading.  We can now exit normally by typing “:q!” since the file is still open as “read-only”.

What the command does:

  • :w = Write a file.
  • !sudo = Call shell sudo command.
  • tee = The output of the vi/vim write command is redirected using tee.
  • % = Triggers the use of the current filename.
  • Simply put, the ‘tee’ command is run as sudo and follows the vi/vim command on the current filename given.