Possible Duplicate:
Redirecting stdout to a file you don't have write permission on

echo "some words" >> /etc/apt/source.list

permission denied

sudo echo "some words" >> /etc/apt/source.list

also return permission denied

Then I think maybe the append operator is another command, I should put the sudo before it, so I try

echo "some words" >> sudo /etc/apt/source.list

also return permission denied

how should I do this task?


sudo sh -c 'echo "some words" >> /etc/apt/source.list'

The reason sudo echo "some words" >> /etc/apt/source.list doesn't work is because sudo is raising the privileges of the 'echo' command, and not the redirection.

The >> redirection causes the current shell to create/append to the file. It fails because your shell doesn't have permissions to do so.

The reason my answer works is that you are running the whole thing (echo and the redirection) in a new shell that has been sudo'd. sh -c ... invokes a new shell and runs the command given in that subshell. The sudo before it makes that subshell run withe escalated privileges.

The second sudo example doesn't make sense, because sudo takes a command to run, and that's not what you are passing. I bet you do have a file in the local directory called sudo now with contents "some words". Feel free to delete that :-)

echo "some words" | sudo tee -a /etc/apt/source.list > /dev/null

-a is for "append to file"; tee usually overwrites the target file. See man tee.


whats wrong in using cat?

sudo cat >> /etc/apt/source.list
some words

but I like using tee as Daniel said :-)

  • 8
    Probably the same as with echo - obviously, the >> fails because it is not included in the sudoification. – glglgl Nov 30 '11 at 10:45
echo "some words" | sudo cat >> /etc/apt/source.list 
  • 2
    Does not work, for the same reason as Nikhil's answer. – Mat Dec 1 '11 at 6:33

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