This happens lot of times. I login as a normal user and start to edit httpd.conf or lighttpd.conf or named.conf in vim / vi text editor. However, I’m not able to save changes due to permission issue (all config files are owned by root). How do I save file without creating a temporary file (/tmp/httpd.conf) and then move the same (mv /tmp/httpd.conf /etc/httpd) as root using vim / vi itself?You can use the combination of tee and sudo command (assuming that sudo is configured for your account) to save a file without creating a third file in /tmp. In this example, you will edit a file called /etc/apache2/conf.d/mediawiki.conf as a normal user:
$ vi /etc/apache2/conf.d/mediawiki.conf
Make some changes and try to save by pressing :w, enter:
To save a file, simply type the following command:
:w !sudo tee %
- :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):
http://www.cyberciti.biz/faq/vim-vi-text-editor-save-file-without-root-permission/
Very nice and useful article! 🙂