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?
[donotprint][/donotprint]You can use the combination of sudo command (assuming that sudo is configured for your account) to save a file without creating a third file in /tmp. This is useful to write a privileged file with sudo command. For example saving a read-only file edited in vim and vi is possible with this trick.
Syntax to save a file in Vim without root permission with sudo
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 %
What the vim and shell command does:
- :w – Write a file (actually buffer).
- !sudo – Call shell with sudo command.
- tee – The output of write (vim :w) command redirected using tee.
- % – The % is nothing but current file name. In this example, it is /etc/apache2/conf.d/mediawiki.conf. In other words tee command is run as root and it takes standard input (or the buffer) and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself):
Update ~/.vimrc file
Open/Edit ~/.vimrc file and append the following code:
" " Sample command W " command W :execute ':silent w !sudo tee % > /dev/null' | :edit!
Save and close the file. Open vim/vi and try to edit a privileged file with:
$ vi /etc/hosts
Now, write a privileged file with custom command just type W:
Now, sudo requires that you authenticate yourselves with a password:
A note about sudo config
Make sure you add yourself to sudo file. Here is my configuration (run ‘sudo visudo‘ OR ‘su -‘ and ‘visudo‘):
# User privilege specification root ALL=(ALL) ALL %admin ALL=(ALL) ALL
Make sure you add yourself to admin group:
# usermod -a -G admin vivek
# id vivek
uid=501(veryv) gid=20(staff) groups=20(staff),80(admin),81(_appserveradm),98(_lpadmin),33(_appstore),100(_lpoperator),204(_developer)
Try vim plugins to write/edit a privileged file or read only file
- User Unix commands including sudo, chmod, and more without leaving vim ever!
- This plugin enables vim to read files, using sudo or su or any other tool that can be used for changing the authentication of a user.
You just learned how to save a read-only file edited in vim text editor. As a sysadmin you might edit a file non-privileged user. In such case you can save file without login as root using the sudo command.