19

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?

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

2 Answers 2

19

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.

4
  • Ok it works. Can you explain me why this works, while my command does not work?
    – ororo
    Dec 15, 2012 at 16:47
  • Done. Hope my explanation makes sense to you. Dec 15, 2012 at 17:39
  • @ororo Don't forget to mark this as the accepted answer if it solved your problem.
    – Dean
    Dec 15, 2012 at 22:37
  • 1
    More generally, this is also how to run a pipeline foo|bar|zip within sudo: sudo bash -c 'foo|bar|zip'. Jan 9, 2019 at 23:22
17

You can use tee:

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

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

Not the answer you're looking for? Browse other questions tagged .