0

If I wanted to do something like

sudo fdisk -l > test.txt

but I wanted test.txt to be under my own user ID (and not root) without having to chown it afterwards, is there a way to do this?

Specifically my actual goal is to have a python script perform a bunch of sudo-permission operations, and dump the outputs. In what way should I ask for sudo permissions if the flow is something like:

somescripts
 \-> runs python script, grabs sudo
      \-> runs operation with sudo permissions
      |     like fdisk -l > test.txt
      \-> runs operation with sudo permissions, reads stdout, writes stdout to file
            like fdisk -l --> reads stdout --> make file --> writes data to file

Thank you.

2 Answers 2

1

You can use tee. What tee does is write stdin to a file and echo it on stdout too. Using it with a pipe and sudo effectively changes the active user for output redirection. Bear in mind that the left side of the pipe must actually write to stdout, not stderr.

sudo fdisk -l | sudo -u myuser tee <file>
3
$ sudo fdisk -l > test.txt
$ ls -l test.txt
-rw-r--r-- 1 daniel daniel 1848 apr 22 14:20 fd

It is not needed to change ownership of the file afterwards when using redirection like you describe.

When using tee as suggested, it is on the same premises not needed to use sudo -u myuser:

sudo fdisk -l | tee test.txt

suffices (but it is not needed in this case as per above demonstration).


In the context of the Python script, if you run the entire script as root via sudo, then the redirection will also be made as root, but if you just use sudo as in the earlier command-line example within the script, then it will behave as above.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .