HowTo: Save A File In Vim / Vi Without Root Permission

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:

Fig.01: Vim Cannot Open File (Permission Problem)

To save a file, simply type the following command:

:w !sudo tee %

Fig.02: Save a file using sudo and 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):

Fig.03: Save and Load File In Vim Again Without Login As Root

http://www.cyberciti.biz/faq/vim-vi-text-editor-save-file-without-root-permission/

This entry was posted in Drugi pišu, Hosting, Linux and tagged , , . Bookmark the permalink.

1 Response to HowTo: Save A File In Vim / Vi Without Root Permission

  1. Very nice and useful article! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.