How to Save a File in Vim After Forgetting to Use Sudo
Many of you probably experienced this. You edit a file in Linux with Vim or Nano or whatever else text editor you might be using and when you try to save, you realise you forgot to launch the editor with sudo privileges, and file can't be written. Exiting without saving and editing again with sudo privileges is not always an option, especially if you lose a lot of work.
Solutions to save a file in vim
There are some workarounds. You can open a new terminal and grant the right permissions on the file with:
sudo chmod 666 <filename>
Now you can go back to your editor and saving will be possible. Don't forget to change back the right permissions for your file.
Also, you could save in a new file and then copy the newly created file over the old one.
But these are workarounds. Vim editor actually offers a solution.
In normal(command line) mode of Vim you can issue:
:w !sudo tee %
And that works like magic. For the geeks, here is how the "magic" works:
- :w - writes the contents of the buffer
- !sudo - pipes it to the stdin of sudo
- tee % - sudo executes tee that writes to "%" file
- % - Vim expands "%" to current file name
So Vim actually makes magic happen.