Automatically capture all stderr and stdout into a file and display on the console

I am looking for a way to capture all the standard output and standard error into a file, as well as output it to the console. So:

(set it up here) set -x # I want to capture every line that executed too cat 'foo' echo 'bar' 

Now the output from foo and bar, as well as the debug output from set -x, will be written to the log file and displayed on the console.

I can’t control how the file is called, so I need to configure it at the beginning of the file.

+4
source share
3 answers

You can use the exec and process replacement to send stdout and stderr inside the script in tee. Process substitution is bugism, so it is not portable and does not work if bash is called as / bin / sh or with -posix.

 exec > >(tee foo.log) 2>&1 set -x # I want to capture every line that executed too cat 'foo' echo 'bar' sleep 2 

Sleep is added to the end, because the output to the console is buffered by a tee. Sleep will help prevent a request from being returned until the output is complete.

+5
source

Perhaps create a proxy script that calls a real script that redirects stderr to stdout and associates it with tee ?

Something like that:

 #!/bin/bash /path/to/real/script " $@ " 2>&1 | tee file 
+1
source

If you only like STDERR on the console, you can:

 #!/bin/bash set -e outfile=logfile exec > >(cat >> $outfile) exec 2> >(tee -a $outfile >&2) # write your code here 
+1
source

Source: https://habr.com/ru/post/1388933/


All Articles