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 :
- file descriptor trick : http://stackoverflow.com/questions/2413166/bash-redirect-and-append-stdout-and-stderr-to-file-and-terminal-and-get-prope
- Closing & opening http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_07 / http://pubs.opengroup.org/onlinepubs/9699919799/
- C More examples for bash,