Save a file you edited in vim without the needed permissions

Posted by on

If you have been working on linux for any amount of time, you would at some time experienced the error:

E212: Can't open file for writing

This means essentially you forgot to include the sudo command before opening the file in question.

There have been a number of solutions to this problem, you can choose the solution that works for you.

Solution 1: Redo all changes but with sudo

This is probably what you do now

:q!
sudo !!

You have to re-create all changes that you did prior to remembering that you needed to open the file with sudo. Obviously this is less than ideal. It does however teach you a lesson ;)

Solution 2: Copy to a temp file

This solution is one level better than the above solution, but still is not optimal as it involves a temporary file

:w /tmp/hosts.temp
:q!
sudo mv /tmp/hosts.temp /etc/hosts

Solution 3: Use tee and sudo

This is the top rated solution on www.commandlinefu.com and involves using tee and sudo:

:w !sudo tee %

This solution does have the advantage that it avoids the temporary file in solution 2, it does however force you to remember a command that is quite complex. Fortunately, there is a solution. First edit your .vimrc file

vim ~/.vimrc

Append on the end of the file

ca w!! w !sudo tee "%"

Now the next time you edit a file without the correct priviledges, you can simply

:w!!

Hope this little tutorial helps you out, if you have any other ideas that can help, please leave a comment below

Cheers