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.
Asked
Active
Viewed 1,887 times
3 Answers
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.

Vincent Scharf
- 71
- 1
- 5
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
-
Tim Pope's [eunuch.vim](https://github.com/tpope/vim-eunuch) also provides `:SudoWrite` & `:SudoEdit` – Peter Rincker Jan 25 '18 at 14:54