Redirect stdout to file and tee stderr to the same file

Viewed 580

I am running a command which will (very likely) output text to both stderr and stdout. I want to save both stderr and stdout to the same file, but I only want stderr printing to the terminal.

How can I get this to work? I've tried mycommand 1>&2 | tee file.txt >/dev/null but that doesn't print anything to the terminal.

1 Answers

If You Don't Need Perfect Ordering

Using two separate copies of tee, both writing to the same file in append mode but only one of them subsequently forwarding content to /dev/null, will get you where you need to be:

mycommand \
  2> >(tee -a file.txt >&2) \
   > >(tee -a file.txt >/dev/null)

If You Do Need Perfect Ordering

See Separately redirecting and recombining stderr/stdout without losing ordering

Related