John
John

Reputation: 961

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:

myscript.sh > /tmp/output.log

In myscript.sh, 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...

Thanks!

Upvotes: 4

Views: 608

Answers (2)

Jubal
Jubal

Reputation: 11

Folks, you seem to be quite fixated on the /proc/*self*/fd. Do consider what exactly does this self mean in the context of your code invocation and if using something like /proc/$$/fd in the script's body wouldn't be a better idea…

(Hint: $(readlink …) is executed in a subshell.)

Upvotes: 0

Petr Skocik
Petr Skocik

Reputation: 60117

$() 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"

Now:

./myscript.sh > /tmp/output.log
echo OUTPUT.LOG
cat /tmp/output.log

should give you:

OUTPUT.LOG
The logfile is: /tmp/output.log

Another option is to think of a way avoid the variable altogether:

echo -n "The logfile is: "
readlink -f /proc/self/fd/1 #goes straight to stdout so no need to capture

Upvotes: 5

Related Questions