1

If you open a file in vi or vim and dont have permissions to write, is there a way to sudo su without having to discard all changes and reopen?

Currently, I have to discard all changes, close vi and then su vi.

Marty Wallace
  • 34,046
  • 53
  • 137
  • 200
  • 3
    Look at this post: http://stackoverflow.com/questions/2600783/how-does-the-vim-write-with-sudo-trick-work . Alernatively when you can't remember the magic incantation presented in there, you could always just :w /tmp/somefilename.txt so at least you don't lose the content. – C. Ramseyer Feb 08 '13 at 20:06
  • Well I mean, as seen above, there are work-arounds, but you should at least just be writing your changes to `/tmp/blah`, and then `sudo cp /tmp/blah dest-file` instead of discarding all your changes each time. – user229044 Feb 08 '13 at 20:07
  • Although you may get some answers here, voting to move this to unix.stackexchange.com as it is more appropriate. Edit: Moving this to unix.stackexchange.com wasn't an option in the flag list. Can a moderator perhaps make the move? –  Feb 08 '13 at 20:17

1 Answers1

1

If you install the Sudo Edit plugin you get the command :SudoWrite which will ask you for your root password. It will then write the file as root, it's very convenient. I use it frequently for editing things in /etc/.

From the documentation:

2.2 SudoWrite                            *SudoWrite*

:[range]SudoWrite[!] [file]

SudoWrite will write the given file using any of the configured methods for
superuser authtication. It basically does something like this: >

     :w !sudo tee >/dev/null file

If no filename is given, SudoWrite will try to write the current file name.
If the current buffer does not contain any file, it will abort.

You can specify a range to write just like |:w|. If no range is given, it will
write the whole file. If the bang argument is not given, the buffer will only
be written, if it was modified.

Again, you can use the protocol handler sudo: for writing.
asm
  • 8,758
  • 3
  • 27
  • 48