Save A File When Not Opened With Root Permission On Vim

This is the scenario.. .

You open a file using `vim` (or `vi`), let us say /etc/apache2/apache2.conf, and start editing furiously. A couple of minutes later you try to save it only to be greeted with an error saying – “E45: ‘readonly’ option is set (add ! to override)”. What a bummer! You have already modified a lot of things at different lines only to remember that you are not logged on as root, nor did you use the sudo command before you opened the file.

On Ubuntu, this is probably very common. I somehow always get myself into this kind of situation and it is quite annoying.

What to do when this happens?

Well you can do the following:

(1) Save it into a temporary file somewhere that your user can write to, or what word processing app jargon calls “Save As” *.

You can do this easily on vim/vi with the command, `:w /path/to/file_name`

Of course, this means that you would have to replace /etc/apache2/apache2.conf with the one in /path/to/file_name. This works, of course. It only takes a few seconds, or literally a few keystrokes, to accomplish. It also gives you the option to backup the original in case you forgot to do that (which you should always do when editing system configuration files just in case the changes you made catastrophically makes your apache server unusable after the restart).

Or you can do this instead.

(2) To save the file, use this command, `:w !sudo tee %`

The effect of this command on vim are,

  • :w – write to file (but of course we already know this, right?)
  • !sudo call the shell sudo command
  • tee output of the write command on vim redirected to shell tee command
  • % just tells tee to use the current file name

In short, you are issuing a `tee` command as root and telling it to write the output of vim to the file currently being edited.


After you press enter. Vim will prompt you with a warning message like the one below.


Either option will save the modifications. But if you plan to continue to edit the file you would want to see reload the one in vim’s buffer, so choose ‘L’ to reload.

Oh, one more thing. Make sure your user is in the sudoers list or this will fail.

And there we have it folks!


* “Save As” for vim is actually with the command :sav as opposed to :w, the difference being the former will replace the current buffer with the new file, whereas the latter will keep the original file open.



Similar Posts:

Notice: This article was published on February 23, 2015 and the content above may be out of date.