sudo echo >> /etc/hosts

`sudo echo` does not give you root write access to files. How do you echo into files as root?

Echo is a valid command stored in /bin:

$ which echo

It is also a built-in function that ships with bash.

However, trying to echo into a file can be counterintuitive.  


$ sudo echo ' hostname.local' >> /etc/hosts
bash: /etc/hosts: Permission denied

The reason for this is the file handler for /etc/hosts is not using the sudo permissions. The sudo echo in this example will execute with root permissions, but writing to the file executes under your own user. Using sudo tee you can get around that:

$ echo ' hostname.local' | sudo tee -a /etc/hosts hostname.local

As you can see we've moved the sudo to the right-hand side of the pipe. This allows us to append (using the -a flag) to /etc/hosts as needed.