Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect output as a different user [duplicate]

I need to sudo as a different used in order to execute a certain command. I am trying to use strace with it and redirecting the output of that into a file for further analysis. The tricky part is that as the sudo'ed user I don't have permissions to write to the location I want to save my file in. (and without sudo'ing I don't have permission to execute that command to begin with).

So how can I execute my command as user A, and redirect it's output as user B?

like image 764
Pavel Avatar asked Jul 02 '12 09:07

Pavel


2 Answers

Try with:

sudo sh -c "command > output.txt"

In this way you should be able to run any command and write everywhere.

If you really need, for some reason I don't understand, execute the command as user A and write as user B, you can do the following:

sudo -u A command | sudo -u B tee /somewhere > /dev/null

Where A and B are the user you want. The > /dev/null part is needed only if don't want command output to be redirected on stdout, too.

like image 197
Zagorax Avatar answered Oct 01 '22 18:10

Zagorax


You can use tee for that. The program reads stdin and writes the input to one or more files as well as stdout:

sudo funny_command | sudo tee output_file > /dev/null

/EDIT: Although you already accepted the other (in my eyes inferior) answer I'll just complete this anyhow:

The use cases above can be done like this

sudo command | sudo tee output.txt > /dev/null
sudo -u A command | sudo -u B tee output.txt > /dev/null

You don't have to use the redirection to /dev/null of course.

like image 21
filmor Avatar answered Oct 01 '22 20:10

filmor