You are not logged in.

#1 2011-04-09 16:53:26

ewaller
Administrator
From: Pasadena, CA
Registered: 2009-07-13
Posts: 20,308

Redirecting output with sudo

Here is one that has been bugging me off and on for some time.

I want to execute a program using sudo, and redirect its output some place to which user invoking sudo does not not have write permission

Simplistically, something like:

JoeUser$ sudo echo "Appended stuff" >> /etc/afile

I understand why this won't work, but for the life of me,  I cannot find an incantation that works.  I think it is complicated by the use of commands that are intrinsic to the shall (cat, echo)

I have been through the zsh and bash manuals and have tried various commands to define a block of code to no avail.

Any hints?


Nothing is too wonderful to be true, if it be consistent with the laws of nature -- Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. -- Alan Turing
---
How to Ask Questions the Smart Way

Offline

#2 2011-04-09 17:26:31

thisoldman
Member
From: Pittsburgh
Registered: 2009-04-25
Posts: 1,172

Re: Redirecting output with sudo

I got this to work:

$ echo "mytext" | sudo tee /etc/myfile

This also worked:

$ sudo bash -c "echo \"more_text\" >> /etc/myfile"

Offline

#3 2011-04-09 19:35:14

tavianator
Member
From: Waterloo, ON, Canada
Registered: 2007-08-21
Posts: 859
Website

Re: Redirecting output with sudo

Hate to tell a forum mod to RTFM, but:

man sudo wrote:

sudo sh -c "cd /home ; du -s * | sort -rn > USAGE"

smile

Offline

#4 2011-04-09 20:05:33

Ramses de Norre
Member
From: Leuven - Belgium
Registered: 2007-03-27
Posts: 1,289

Re: Redirecting output with sudo

echo "foo" > bar     ->    echo "foo" | sudo tee bar
echo "foo" >> bar    ->    echo "foo" | sudo tee -a bar

Offline

#5 2011-04-09 20:41:48

ewaller
Administrator
From: Pasadena, CA
Registered: 2009-07-13
Posts: 20,308

Re: Redirecting output with sudo

tavianator wrote:

Hate to tell a forum mod to RTFM, but:

man sudo wrote:

sudo sh -c "cd /home ; du -s * | sort -rn > USAGE"

smile

If the shoe fits....

Thanks everyone.  The pipe works in a lot of cases.
Invoking bash with sudo and passing commands is the obvious way (once someone points it out).  I guess I could not break out of the box I had built in order to look at the problem from a different angle.


Nothing is too wonderful to be true, if it be consistent with the laws of nature -- Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. -- Alan Turing
---
How to Ask Questions the Smart Way

Offline

Board footer

Powered by FluxBB