afkkqw
Last Updated: February 25, 2016
·
2.043K
· bendihossan
A06c38dd3377bbc0db360c44a2969fed

Add sudo after opening a file in vim

I often type 'vim /path/to/file' without thinking if I need sudo or not. But you can add sudo powar afterwards with:

:w !sudo tee %

You'll have to enter your password of course and then press enter a couple of times to confirm the process. That will write your changes to the file with sudo. If you try to quit out vim will warn you don't have permissions. You can just ignore that with :q!

Remember, with great power comes great responsibility :)

Say Thanks
Respond

5 Responses
Add your response

1155
C630f26c1d202baa5af6bde5b7eeb8bb

Yeah, I visit http://www.commandlinefu.com/commands/browse/sort-by-votes every time I need this command. Somehow it's too difficult to remember.

over 1 year ago ·
1171
A06c38dd3377bbc0db360c44a2969fed

@ilzoff You're right, vim commands are often difficult to remember at the best of times. Practice makes perfect though and I'm well-practiced in forgetting to type 'sudo' :)

over 1 year ago ·
1923
B5c7599bfa993fc0164d4a3b60ede8a4

Train yourself with this in your local vimrc:

command! Sudo echo "w !sudo tee % >/dev/null"

Then :Sudo will remind you what the command is every time and drill it in to your brain; of course, if you're only using this on a single machine or you have your vimrc in a source control repo that's easy to install:

command! Sudo w !sudo tee % >/dev/null
over 1 year ago ·
2984
Afe6a9de6c4bcdc99f6b5e3990a58b38

tpope's vim-eunuch plugin has a :SudoWrite command:

https://github.com/tpope/vim-eunuch/blob/master/doc/eunuch.txt

over 1 year ago ·
15503

Add this to the .vimrc:

cmap w!! w !sudo tee > /dev/null %

Now typing w!! will save it with sudo. No need to remember the whole thing.

over 1 year ago ·
Filed Under