Wednesday, November 16, 2011

Saving a root owned file as normal user from within Vi/Vim

This happens lot of times. I login as a normal user and start to edit root owned file in vim / vi text editor. However, I'm not able to save changes due to permission issue (all config files are owned by root). So to save file, i can do :w !sudo tee % where
:w - Write a file.
!sudo - Call shell sudo command.
tee - The output of write (vim :w) command redirected using tee. The % is nothing but current file name i.e. /etc/apache2/conf.d/mediawiki.conf. In other words tee command is run as root and it takes standard input and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself):

No comments: