6

I want to do something along the lines of:

echo "Append string" >> protected_file

However, as this file is write protected I get an error. Running:

sudo echo "Append string" >> protected_file

seems to run sudo on the echo command, and still gives me the permission error, how do I append to this file?

1
  • 1
    You should sudo your shell script, not the echo command.
    – Raptor
    May 22, 2012 at 8:57

4 Answers 4

11
echo "Append string" | sudo tee -a protected_file >/dev/null
3
  • 1
    +1 for this -- unlike the accepted answer, it doesn't give extra privileges to anything that doesn't need them, which would be important if the content were generated by something more complicated than echo. May 22, 2012 at 16:16
  • 1
    Why is the >/dev/null necessary?
    – Richard
    May 23, 2012 at 6:04
  • 1
    @Richard: Because tee sends output to the file and to standard out (two places - like a "tee" in a pipe) and we don't want the extra output. Redirecting standard out to /dev/null discards it. May 23, 2012 at 10:48
3

For a literal answer,

sudo sh -c 'echo "Append string" >> protected_file'

But I agree with ShivanRaptor in principle.

Explanation: >> is a shell operator. If you invoke sudo command, you do not run another shell; thus you cannot redirect echo without also redirecting sudo (which, ultimately, gives you the wrong user id when doing the redirection). The trick is to launch a separate shell inside sudo, where you can issue the redirection operator.

1
  • Thanks, but this is just a single command I wrote on the cmd line, not inside a shell script
    – Richard
    May 22, 2012 at 9:09
0

or try this:

echo "echo 'append string' >> protected_file" | sudo bash
0

Putting it all together and fixing one of the answers, there are 3 ways:

sudo su root -c "echo 'append string' > protected_file"
echo "echo 'append string' >> protected_file" | sudo bash
echo "append string" | sudo tee -a protected_file >/dev/null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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