Last Updated: January 12, 2021
·
3.829K
· bendihossan

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 :)

5 Responses
Add your response

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 ·

@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 ·

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 ·

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

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

over 1 year ago ·

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 ·