Saving file with vi when forget to sudo

This is a little lifehack I found recently. For sure you ended up, at least once, in a situation when provided some changes to file in vi and then realised that you forget to open editor as a superuser.

vi1

In such situation, you don’t really need to leave your editor. You can easily gain root just for writing operation.

Vi let’s you invoke any shell command when you are in. So for example, you can check if your script is working correctly, just after providing changes and get back to it’s source, just when it ends execution. All shell commands are invoked with¬†exclamation mark prefix, ie. !echo "This is a test"

In our case we need to use linux tee command, which takes standard input and puts it into standard output and may also put it in a specified file.

vi2

By invoking `:w !sudo tee %` we are trying to use editor’s function to write into the file, which should fail. But after that sudo and tee commands come into play, take file’s path (percent file points to file which is being written to by vi) and puts standard input (from the editor) into the file (and also into command mode). After that, vi should notify us that file content has been changed and offer us to reload it.

 

Leave a Reply

Your email address will not be published. Required fields are marked *