Cbhihe Cbhihe - 7 months ago 25
Bash Question

Redirect _sudo_ 's PID, stderr and stdout to file

How can

_user_
redirect
PID
as well as
stdout
and
stderr
of
sudo
(and not of the sub-shell it spawns) to file ?


I.e. the
sudo
passwd request (
[sudo] password for _user_: _
) and any error normally sent to the current shell's
stdout
and
stderr
by
sudo
should be redirected to any appropriate file
/path/foobar
, in the spirit of:

{sudo-process} &> >(tee /path/foobar > /dev/null)
or

{sudo-process} 2>&1 | tee /path/foobar &>/dev/null)


as far as
stdout
and
stderr
are concerned. In my use case,
PID
is also needed to make unattended killing of the
sudo
process possible from an external script with appropriate privis.

By "current shell", I mean the shell in which the
sudo
process lives.
The farthest I got to is a possible
askpass
program (see option
-A
in man 8 sudo) and the possibility to use
plugins
which may or may not be relevant. I have no experience at all with that. Can you help ?




Note: I am NOT looking at redirecting output from a shell spawned by
sudo
to file. As in:

$ sudo cmd &> /path/foobar
or
$ sudo sh -c 'cmd &> /path/foobar'


depending on whether
/path/foobar
is a file with appropriate write permission, i.e. accessible to
cmd
's redirection of
stdout
and
stderr
. This is not the issue.

EDIT:

@JohnKugelman suggests running
sudo -n
which causes
sudo
to emit an error message to
stderr
and to die, in case a passwd is needed. That takes care of:

- redirecting
stdout
, since there is none anymore.

- the need to store
sudo
's PID, since the process dies on its own.

The main issue remains: how to redirect
sudo
's
stderr
to file ?

Answer

To redirect sudo's stderr to file:

sudo -n cmd -- &> /path/of/the/file