Pages

Tuesday, October 9, 2012

vim trick #2

Yet another very useful vim trick: do you ever open a system config file but forget to open it with sudo? You make the changes but then, when it's time to save it, you're hosed. You have to save as a temp file, then move it to the right place, a whole lot of ugly. Well, not anymore! Put this in your .vimrc file and save with :w!! instead of :w. That's it!
cmap :w!! %!sudo tee > /dev/null %
What this does is sends the current file to 'sudo tee'. Now, tee here is used as a hack, as its regular function is to both redirect input to a file and to standard output. We are not interested in the standard output so we pipe that to /dev/null (otherwise it shows up in the vim window), and tell tee to overwrite the file we have open, with sudo power. One last thing is, vim will ask you to reload the file, because it was modified outside of the editor (duh!), so go ahead and do that. Nifty, eh?

No comments:

Post a Comment