views:

1635

answers:

5

This is a pretty simple question, at least it seems like it should be, about sudo permissions in linux.

There are a lot of times when I just want to append something to /etc/hosts or a similar file but end up not being able to because both > and >> are not allowed, even with root.

Is there someway to make this work without having to su or sudo su into root?

+1  A: 
sudo sh -c "echo 127.0.0.1 localghost >> /etc/hosts"
Vinko Vrsalovic
+13  A: 

The problem is that you are redirecting the output which falls outside of the sudo permission boundaries.

try this:

sudo sh -c "echo 'something' >> /etc/privilegedfile"

Matt P
What are "sudo permission boundaries"? It's just the shell which parses the redirection operator with higher precedence than a command for obvious reasons
Vinko Vrsalovic
+4  A: 

The issue is that it's your shell that handles redirection; it's trying to open the file with your permissions not those of the process you're running under sudo.

Use something like this, perhaps:

sudo sh -c "echo 'something' >> /etc/privilegedFile"
Incident
+1  A: 

Doing

sudo sh -c "echo >> somefile"

should work. The problem is that > and >> are handled by your shell, not by the "sudoed" command, so the permissions are your ones, not the ones of the user you are "sudoing" into.

agnul
+6  A: 

another workaround using tee:

echo 'deb blah blah # blah blah' | sudo tee -a /etc/apt/sources.list

avoiding quotes inside quotes.

RamyenHead
I absolutely prefer this one. It's just the simplest (and it tought me about tee, which comes in handy in other scenarios as well).
Joachim Sauer
I agree. Seems neater than start a new sh too, especially with potentially to do things with environment etc.
Sam Brightman