5

I need to redirect stdout to console along with stdout and stderr redirected to a file. This needs to be done inside a shell script. I found the below code to redirect both to console and log file, now I need to remove stderr to console.

exec > >(tee -i "output.log") 2>&1

Could you please help me here?

Alan Thomas
  • 51
  • 1
  • 4
  • As an added complication, remember that stdout is usually buffered, while stderr is usually not. Redirecting both to a common log will likely cause then to be written out of actual chronological order. One way to deal with that is to unbuffer both, such as by routing both to stderr, but this complicates your solution a bit more. Why would you not want stderr also going to the console? That seems counterintuitive to me. – Paul Hodges Jun 25 '21 at 14:12
  • Yea, that's what I was thinking. Especially with multithreading, where it might find an error and start to generate a report before other tasks are complete. – Doyousketch2 Jun 26 '21 at 13:21

3 Answers3

2

Derived from this answer: How do I get both STDOUT and STDERR to go to the terminal and a log file?

I tested the following code:

echo '' > out.log
exec 1> >(tee -a -i out.log) 2> >(tee -a -i out.log > /dev/null)
>&2 echo yay
echo nay

The STDERR content goes to file and not to console, and STDOUT goes to both.

1

I think you should launch it like this:

your-command 2>&1 | tee -i "output.log"

It will pipe both stdin and stderr to tee -i output.log, which will echo text before writing.

Or, to ignore stderr (pipe to /dev/null):

your-command 2>/dev/null | tee -i "output.log"

Or your command modified with /dev/null redirection:

exec > >(tee -i "output.log") 2>/dev/null
Vlad Havriuk
  • 1,291
  • 17
  • 29
0

It'd be something like this, but you don't have to tee that second one.

exec 1> >( tee stdout.txt ) 2> stderr.txt

output 1 is tee'd so you see it on screen, and in stdout.txt
errors 2 just goes straight to stderr.txt

Doyousketch2
  • 2,060
  • 1
  • 11
  • 11
  • 1
    I believe you can use the same text name, if you want them to both be redirected into there, but I don't know how two streams would resolve during crashes. Messages might overlap. You're welcome to try, but that sounds like Ghostbusters to me, "don't cross the streams." – Doyousketch2 Jun 25 '21 at 07:37