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

I am trying to append a line of text to a write protected file.

I tried to accomplish this with sudo echo "New line to write" >> file.txt but I get a permission denied error — presumably because it is trying to sudo the string, not the act of appending it to a file.

If I run sudo vi file.txt and authenticate I can happily write away.

Any help would be greatly appreciated.

  • 1
    Did you mean sudo echo "New line .. in your post? – Levon Jul 11 '12 at 11:28

Use the command below

echo "New line to write" | sudo tee -a file.txt
| improve this answer | |
  • 1
    If you're concatenating a lot of data, and/or you're on a particularly slow (or expensive) connection, you should add >/dev/null to the tee side of the pipe. – Alexios Jul 11 '12 at 14:38

I always do such stuff like this: su -c "echo \"Appended.\" >> test.txt" (and I'd be happy to learn how (if) it differs from those other solutions).

| improve this answer | |

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