15

I'm using Amazon Linux. I'm trying to append some text onto a file. The file is owned by root. I thought by using "sudo", I could append the needed text, but I'm getting "permission denied", see below

[myuser@mymachine ~]$ ls -al /etc/yum.repos.d/google-chrome.repo
-rw-r--r-- 1 root root 186 Jul 31 15:50 /etc/yum.repos.d/google-chrome.repo
[myuser@mymachine ~]$ sudo echo -e "[google-chrome]\nname=google-chrome\nbaseurl=http://dl.google.com/linux/chrome/rpm/stable/\$basearch\nenabled=1\ngpgcheck=1\ngpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub" >> /etc/yum.repos.d/google-chrome.repo
-bash: /etc/yum.repos.d/google-chrome.repo: Permission denied

How can I adjust my statement so that I can append the necessary text onto the file?

31

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'
| improve this answer | |
2

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'
| improve this answer | |
  • This does not add anything of value that the accepted answer does not already have. Ravexina included a bash -c example in their answer (which pretty much does the same thing as su -c) so this one is really completely unnecessary. – MD XF Aug 1 '17 at 2:59
  • It shows another way of completing this task that is not mentioned in any of the other answers. Consider also when bash is not installed, this is more like sudo $SHELL -c '...'. Furthermore, the other answer doesn't use echos escape option (not that the OP would miss that). That said, this whole question doesn't add anything. Hence, I flagged it as a duplicate. – rlf Aug 1 '17 at 13:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.