Saturday, April 27, 2013

[Linux] Redirecting output with sudo

ref: http://notfaq.wordpress.com/2007/09/26/unixlinux-redirect-output-as-sudo


Unix/Linux — Redirect output with sudo

By 
Sometimes you might need to redirect the output with sudo privileges. For example:
echo myhost.com > /etc/hostname
will give you the following error:
-bash: /etc/hostname: Permission denied
Unfortunately, using:
sudo echo myhost.com > /etc/hostname
will give the same error.
The solution is to start bash as sudo and then give the entire command tobash as input:
sudo bash -c “echo myhost.com > /etc/hostname”
Or as one reader suggested:
echo myhost.com | sudo tee /etc/hostname