Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
add comment

marked as duplicate by Michael Mrozek Nov 30 '11 at 19:06

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.

4 Answers

up vote 15 down vote accepted

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 :-)

share|improve this answer
add comment
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.

share|improve this answer
add comment

whats wrong in using cat?

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

but I like using tee as Daniel said :-)

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

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