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. This is useful to write a privileged file with sudo command.
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):
Update ~/.vimrc file
Open/Edit ~/.vimrc file and append the following code:
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)
Optional: Try vim plugins to write/edit a privileged 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.