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):
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012
- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop