4

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?

mko
  • 143

4 Answers4

15

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

Danny Dulai
  • 1,968
10
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.

daniel kullmann
  • 9,527
  • 11
  • 39
  • 46
-3

whats wrong in using cat?

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

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
-3
echo "some words" | sudo cat >> /etc/apt/source.list 
Mat
  • 52,586