Take the 2-minute tour ×

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

share|improve this question
add comment

2 Answers

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"
share|improve this answer
FWIW I think pixelbeat's answer is better than mine ;) I forgot about tee –  Oktalist Sep 1 '12 at 13:36
can you detail a bit, like why tee is a better solution to this? –  Richard Sep 1 '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 1 '12 at 19:34
add comment

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

echo 'blabla' | sudo tee -a /root/.profile
share|improve this answer
add comment

Your Answer


