Unix/Linux — Redirect output with sudo
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