VIM: Saving with sudo, without opening with sudoPosted: August 20, 2013 Filed under: Uncategorized | Tags: development, sudo, vim Leave a comment
It happens all the time. You open a file in VIM, you make three and a quarter trillion changes, and then realize you needed sudo but didn’t use it when you opened the file. What do you do?
Well, if you might save the file under a new name, then quit, delete the original and rename the new file with the original name. It works, but its really annoying.
Luckily there is a cool trick in VIM that lets you save with sudo, even after having opened a file without it. Here it is.
:w !sudo tee %
Hit enter after typing that in, you will be prompted for a password if necessary, and then you will then get the following message.
Press ENTER or type command to continue
Go ahead and hit enter, and assuming you actually made some changes, you will then get the following message.
Press ENTER or type command to continue W12: Warning: File "sites-available/webgrind.conf" has changed and the buffer was changed in Vim as well See ":help W12" for more info. [O]K, (L)oad File:
This is just telling you there are two versions of the file, the old one and the new one and gives you an option to simply acknowledge, or to load the new version. You are typically going to want to enter “L”.
Thats it, your file should be saved now. Cool trick, saved me some frustration many time.
Note: I first heard of this trick at WordCamp, but I can’t remember who it was that mentioned it.