1

I want to append some text to a privileged file /root/.profile. I used following scripts to do so.

sudo echo "blabla" >> /root/.profile

it still complains with permission denied. What is the right way to do so? I am using bash4 on ubuntu12.04

Richard
  • 14,642
  • 18
  • 56
  • 77

2 Answers2

5

The stream redirect >> is evalutated before sudo is even called. The simple answer is to put the whole thing inside a sub-shell:

sudo sh -c "echo 'blabla' >> /root/.profile"
Oktalist
  • 14,336
  • 3
  • 43
  • 63
  • FWIW I think pixelbeat's answer is better than mine ;) I forgot about `tee` – Oktalist Sep 01 '12 at 13:36
  • can you detail a bit, like why ``tee`` is a better solution to this? – Richard Sep 01 '12 at 14:27
  • @Richard firstly spawning a new `tee` process is probably less expensive than spawning a new `sh` process, secondly having two levels of quoting can get confusing if you are doing variable substitutions inside the quotes. If you are doing any variable substitutions inside the quotes then watch out for execute-arbitrary-code-as-root vulnerabilities! There might be some situations where my answer is more appropriate than pixelbeat's, but probably not many. – Oktalist Sep 01 '12 at 19:34
4

Yes the shell will open /root/.profile before running sudo. You need something like:

echo 'blabla' | sudo tee -a /root/.profile
pixelbeat
  • 30,615
  • 9
  • 51
  • 60