Pipe stderr to file and screen without redirecting stderr to stdout

In a bash script I'd like to execute a command while piping the stderr to both a file and to the terminal. However, I want stderr to stay on the '2' file descriptor so that I can parse it from an external process that is calling this bash script.

All the solutions I've seen so far involve swapping stdout with stderr and then tee'ing to another file, for example:

find /var/log 3>&1 1>&2 2>&3 | foo.file

If I am to call this script from another one, the stderr will go to stdout and stdout will go to stderr, which is no good for me. I've tried to swap them again like so:

find /var/log 3>&1 1>&2 2>&3 | foo.file 4>&1 1>&2 2>&4

but this doesn't work.

1 Answer

I found out how to do it in the end, following advice from this page. I need to redirect stderr to tee then redirect the output of tee back to stderr.

find /var/log 2> >(tee foo.file >&2)
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like