I made lengthy changes to a configuration file on a Ubuntu Linux computer with the vi editor. Unfortunately, I forgot to sudo first, so now I'm in the editor, but can't save my changes because of missing rights. Can I retroactively sudo the user on that terminal, or what would be the best course of action to take?


In this case, I write the file with :w /tmp/tmpfile. Then I go out and move /tmp/tmpfile to my old file with sudo rights.

  • this is what i end up doing, but i like wfaulk's answer .. if i can only remember it the next time i do this! :) – quack quixote Apr 19 '10 at 14:59
  • I hope you copy the file rather than moving it. Moving replaces the file’s mode (permissions) with vi’s default (which is probably 666, ANDed with the inverse of your “umask”), replaces the file’s owner with your UID (it was “root”, wasn’t it?), and breaks hard links. – Scott Jun 23 '14 at 23:20
  • A couple of issues: (1) If the file is supposed to be confidential, and your “umask” is 22 (rather than 66), this procedure exposes the file’s contents to other users who might be monitoring the /tmp directory. (2) If you have truly evil users on your system, they could replace your /tmp/tmpfile between when you write it (from vi) and when you copy it over the system configuration file that you were editing. It’s safer to put the temporary file into a directory that only you have access to. – Scott Jun 23 '14 at 23:33

From SO:

:w !sudo tee %

I actually find myself using this way to do it more frequently now:

:%!sudo tee %

I think it's a little more intuitive, as I know what :%! does, whereas I don't have a visceral understanding of :w !. Also, it's easy to miss the very important space between the w and the !.

  • 2
    If it helps your intuition any, remember that vi commands can be multiple letters, so there could theoretically be a “wfoo” command, so if you want to write to a file called “foo”, you must say “:w foo”. I.e., you need a space after “:w”. As far as “:w !” is concerned – you know what “:!” is, right? “:!date” runs a “date” command. So “:w !xyz” writes the buffer, but to a command rather than to a file. – Scott Jun 23 '14 at 23:26
  • This should be made the accepted answer as the current existing answer is a rather long work-around whereas this is an immediate solution. OP? – bschlueter Mar 19 '15 at 4:15

Couldn't you open another terminal and temporarily change the file's access rights?

  • 1
    This is a bad idea. Probably wont ever be a big security problem, but it could be, and there's better and simpler solutions (like writing to a temporary file, or better, the :w !sudo tee % solution wfaulk posted – dbr Oct 10 '09 at 20:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.