Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I have tried:

sudo "some string" >> test.txt

But am being denied permission.

Can anyone help?

share|improve this question

3 Answers 3

up vote 10 down vote accepted

Depends on how much access your administrator has given you via sudo. The simplest answer, assuming that you have permission to do so, is to run "sudo -s" to get a privileged shell and then just do your

echo somestring >> test.txt

as 'normal'. If you need to do it automatedly:

sudo /bin/sh -c 'echo somestring >> test.txt'

The reason that what you have won't work (other than the fact that you left what I assume to be an "echo" command out) is that the file redirection happens in the context of your shell and the sudo only applies to the command you told it to run.

share|improve this answer
have you considered sudo -s instead of firing up /bin/sh explicitly? –  Nerdling Sep 24 '09 at 21:34
Yes. It's the first option I list. –  wfaulk Sep 24 '09 at 21:37
% echo "string" | sudo tee -a test.txt
share|improve this answer
Has the side effect of echoing the string to stdout, but nice and short... –  freiheit Sep 24 '09 at 21:50
if you don't want to echo to stdout echo "string" | sudo tee test.txt > /dev/null –  Aaron Brown Sep 24 '09 at 22:08
the real value of 'tee' is that all the 'work' is done in the context of the normal user and only the output is written with 'sudo' powers. for me thats more important than the shortness and more 'correct' than the other answers, allthough they work of coz. –  akira Sep 24 '09 at 22:14
It's a good solution. –  wfaulk Sep 24 '09 at 22:32
+1 This is the best solution because the main part of the command executes with limited privilege, and only the output gets written as root. –  lukecyca Sep 25 '09 at 0:01
sudo bash -c "echo 'some string' >> test.txt"

The problem in your original try is that the ">>" is happening in the shell running as you; bash opens the file, not whatever is being run by sudo. In my version, you're passing the whole command including the redirection to a bash run by sudo.

share|improve this answer
have you considered sudo -s instead of firing up /bin/sh explicitly? –  Nerdling Sep 24 '09 at 21:35
Nerdling: On my systems, "sudo -s" runs the shell you specify, it doesn't really support running complicated multi-argument things like this. –  freiheit Sep 24 '09 at 21:47

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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