Peter's Blog

Redefining the Impossible

Items filed under sudo


I found the best tip ever.

Scenario: hop into /etc and start editing any file using vim of course. Go to write the file and find it's read only: bugger forgot to launch vim with sudo vim or sudoedit. This happens to me around 50 times a day.

Solution:

:w !sudo tee %

I had to go through various man pages to understand this one:

:w ! execute a command, sending it the contents of the current file

sudo run the command as root. The contents of the file being edited get passed through sudo to the command that sudo launches

tee the tee command is normally used to allow one to view text that is being pumped to stdout while also saving it to a file. Here it is being used primarily to write from stdin to a named file. cat > % does not work because the '> %' part is run as the pleb user, not the superuser.

% vim replaces this with the name of the current file

It has the downside that the output of tee that is sent to stdout is fed back into vim so vim will wave it at you unless you type in

:w !sudo tee % > /dev/null

which is far too much typing.

vim will also prompt you that the file has changed and do you want to reload it.

HOWEVER the good thing about this tip is that it is short enough to remember and doesn't need any plugins installed or .vimrc files editing and hence can be used immediately on half a dozen different accounts.


Filed under: sudo vim