17

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.

Toby
  • 3,973
  • 4
  • 20
  • 16

2 Answers2

25

Use the command below

echo "New line to write" | sudo tee -a file.txt
Manula Waidyanatha
  • 2,263
  • 20
  • 12
  • 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
4

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

Emanuel Berg
  • 6,763
  • 7
  • 43
  • 65
  • How it differs from the other solution is that it doesn't output to stdin. So it would effectively be the same as the very awkwardly written `echo "bla" | sudo tee -a file.txt > /dev/null`. – Fabian Röling Jan 18 '21 at 02:18