John John - 1 year ago 130
Linux Question

Linux file descriptor - getting current redirection stdout file?

I'm trying to get the current stdout redirection, and having some trouble.

I have a script that is always run with stdout redirection ie: > /tmp/output.log

In, I need to find out what file it is being output to.

I'm trying this currently (not working):

logfile=$(readlink -f /proc/self/fd/1)

That's outputting logfile = /tmp/sflq.r3f, for instance. I need to instead find that it's going to /tmp/output.log

Is this even possible?

I'm using korn shell if it matters...


Answer Source

$() uses a pipe (or as it appears for ksh -- a tempfile which ksh appears to use to emulate what usually is a pipe in other shells) to capture the output of readlink.

Inside $(), the stdout is that pipe (or tempfile in ksh's case).

You can get around this interposed stdout file with something like:

{ logfile=$(readlink -f /proc/self/fd/3); }  3>&1
# my ksh 93 needs the { ;} -- dash, and zsh don't 
echo "The logfile is: $logfile"


./ > /tmp/output.log
cat /tmp/output.log

should give you:

The logfile is: /tmp/output.log
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download