bash: redirect stderr to file and stdout + stderr to screen
With a recent bash, you can use process substitution.
foo 2> >(tee stderr.txt)
This just sends stderr to a program running tee.
More portably
exec 3>&1
foo 2>&1 >&3 | tee stderr.txt
This makes file descriptor 3 be a copy of the current stdout (i.e. the screen), then sets up the pipe and runs foo 2>&1 >&3
. This sends the stderr of foo to the same place as the current stdout, which is the pipe, then sends the stdout to fd 3, the original output. The pipe feeds the original stderr of foo to tee, which saves it in a file and sends it to the screen.