Pipelining

My problem is more a question of how to do it more elegantly than how to do it at all. The problem:

I have a pipeline which has to write to the screen AND to a logfile:

proc1 | tee -a <logfile>

What makes things difficult is i also need the return code of proc1. But

proc1 | tee -a <logfile> ; print - "$?"

will only display the exit code of tee, not of proc1. Of course I could use a solution with an intermediate file like:

proc > tmpfile ; RC=$?
cat tmpfile | tee -a <logfile>
print - "$RC"
rm tmpfile

This solution would work but even not taking into account that the output is displayed after instead of concurrently to the execution of proc1 to me it looks clumsy and I'd be thankful for input on how to do it better.

Thanks

bakunin

You have taken correct way. $? will give status of prev command. we can not make it with single utility to give return code and redirect output to another log file. You can do it better as,

# proc > logfile
RC=$?
tee -a <logfile> < logfile
print "$RC"

where, < <filename> is faster than cat <filename>

That is all.

exec 3>&1
RC=$(exec 4>&1;{ proc;echo $? >&4; }|tee -a logfile >&3)
exec 3>&-
echo $RC

Many thanks to r2007 for this solution. Yes, this looks elegant enough even for my jaded taste. ;-))

bakunin

Can someone please explain this code.
I know that file handles 1 for stdout and 2 for stderr. what are 3 and 4?
How does the first three lines of code achieve the result that bakunin wanted of returning the result of execution of proc? :confused:

It duplicates the file descriptor 1.

Lets start with known examples.

You know what 2>&1 stands for. It redirects stderr to standard output. On those lines, are 3>&1.

Check out these links for posts on similiar lines.

http://www.unix.com/showthread.php?t=15976
http://www.unix.com/showthread.php?t=14308

The bash manpage has those documented. Check the sub-topics under REDIRECTION.

Happy learning !

Vino

RC contains the status of the tee command.

Another way:

#! /bin/ksh
(proc; echo $? > status_file) | tee -a logfile
RC=$(<status_file)

Jean-Pierre.