3

I vim somefile.txt often without using sudo. Is it possible to use sudo within an open vim session so you don't have to close the file and reopen? New to Vim and Linux in general so any help is very appreciated. Thank you.

3 Answers3

2

Well seems like I was late to the party. As said you should use :w !sudo tee % to switch to sudo. If you would like to change the permissions of the file so you will not need sudo again you could use :!chmod +w % in command mode with %getting replaced by the filename to change the permissions of the file afterwards, as stated here: How to change file permission from within vi.

1

I have this in my .vimrc, so that a :W will write with sudo access.

" :W sudo saves the file                                                                                  
command W w !sudo tee % > /dev/null`
Joe
  • 7,378
  • 4
  • 37
  • 54
1

You can use the SudoEdit plugin; it provides a :SudoWrite command.

There's also a trick of :write to a process of !sudo tee, passing the current file name; it is explained here.

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324