How to get the return value of "
command1" if passed to a "
| command2" , for example
"| tee OUTFILE" :
command1 | tee OUTFILE
With recent shells, you can use the array storing this : bash is
${PIPESTATUS[x]} , zsh is
$pipestatus[x] to get this value :
command1 | tee OUTFILE
echo ${PIPESTATUS[0]}
With older shells, this feature is not available, but you still can use posix features and play around with the file descriptors :
exec 4>&1; RETVAL=$({ { command1 ; echo $? >&3 ; } | { tee $OUTFILE >&4; } } 3>&1); exec 4>&-
Explainations
- Create a file descriptor fd4 and map it to STDOUT
- Fill the RETVAL
value with the fork.
- fd4 is transmitted, but STDOUT and STDERR are
recreated for the forked process so fd4 still exist and is available.
- create the fd3 and redirect it to STDOUT
- map 'tee' STDOUT to the
previously created fd4 so that it gets printed to the terminal;
- tee then
forks the piped 'command1' which output value $? is sent to
fd3 with 'echo $? >&3', and hence outputed in the RETVAL
variable;
- Eventually, close the fd4
References :