If you’re trying to do something from the command line and don’t have permissions, you can (dependent upon your shell environment) hit the up arrow to go back to the last command in your history, then hit the home key to get to the beginning of the line, and finally type “sudo” in front of everything. Or you could just type:
sudo !!
Pretty simple right? it’s just executing the last command, but doing it with sudo. Practically the same thing.
But have you ever opened a file vi vim/vi but didn’t notice it was opened read-only until you went to save the changes?
E45: ‘readonly’ option is set (add ! to override)
You don’t have to exit and run sudo in front of the same command again, or use the sudo double bang. Instead, take advantage of this little known trick:
:w !sudo tee %
You’re tee’ing the changes using the % file name replacement so you don’t have to supply the file name you’re currently editing. There’s a space after the ‘w’ and no spaces between ‘!’ and ‘sudo’. Once tee finishes writing out the file, vim will notice its contents have changed and ask you to continue or load. It doesn’t really matter which one you choose at this point because you’re just going to exit now anyway.
W12: Warning: File “fstab” has changed and the buffer was changed in Vim as well
See “:help W12″ for more info.
[O]K, (L)oad File:
I found this almost by accident. I was originally trying to do something like this:
:w !sudo grep '' > %

…but the grep was ending and the redirection happens outside of sudo, so that’s no use and it’s not easy to remember. But along came tee. Another useful way of using tee is to capture stderr and stdout at the same time with a pipe:
run something 2>&1 | tee -a $log
If you’ve tried to redirect output of a command using sudo, you’ve probably noticed the redirection happens as the normal user. If you want to redirect something so that root is the owner, add -s in front of your command and enclose the whole thing in quotes.
sudo "run something 2>&1 | tee -a $log"
Posted by admica @ 29 September 2010