Getting "permission denied" when trying to append text onto a file using sudo
You have to use tee
utility to redirect or append streams to a file which needs some permissions, like:
echo something | sudo tee /etc/file
or for append
echo something | sudo tee -a /etc/file
because by default your shell is running with your own user permissions and the redirection >
or >>
will be done with same permissions as your user, you are actually running the echo
using the sudo
and redirecting it without root
permission.
As an alternative you can also get a root shell then try normal redirect:
sudo -i
echo something >> /etc/pat/to/file
exit
or sudo -s
for a non-login shell.
you can also run a non interactive shell using root access:
sudo bash -c 'echo something >> /etc/somewhere/file'
The explanation given in the previous answer is basically correct. The command before the redirection is run with elevated privileges, but not the redirection itself.
Here is another method which will do what you want. It has not been mentioned here or in the answers to the question that this is a duplicate of. I include it here for completeness.
sudo su -c 'echo -e "some\ntext" >> /other/file'