Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Possible Duplicate:
sudo & redirect output

Let's say I want to add some line into /etc/profile. I try:

$ sudo echo "something" >> /etc/profile
bash: /etc/profile: Access forbidden

Of course I could write:

$ sudo su
# echo "something" >> /etc/profile

and this works, however it does not work within a shell script.

So, what is the right way?

share|improve this question

marked as duplicate by Lekensteyn, hhlp, fabricator4, Ringtail, fossfreedom Dec 16 '12 at 0:30

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

imho, it is better to run the whole script as root rather than have sudo commands in it. – Pavel A Dec 15 '12 at 17:49

Your version:

sudo echo "something" >> /etc/profile

In this command, echo is run as root, but the shell that's redirecting echo's output to the root-only file is still running as you. That's why you are getting "Access forbidden"

Working version:

sudo bash -c 'echo "something" >> /etc/profile'

In this command you use sudo to start a new shell with root privileges and then give that shell the whole command string (including the redirection) with the -c option of bash.

share|improve this answer
Ok it works. Can you explain me why this works, while my command does not work? – ororo Dec 15 '12 at 16:47
Done. Hope my explanation makes sense to you. – Andy Friese Dec 15 '12 at 17:39
Makessens, thank you! – ororo Dec 15 '12 at 20:41
@ororo Don't forget to mark this as the accepted answer if it solved your problem. – Dean Dec 15 '12 at 22:37

You can use tee:

$ echo "something" | sudo tee -a /etc/profile

If you omit the -a (append) the file will be overwritten.

share|improve this answer

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