I want to log stdout and stderr with timestamp to a log file and view it on screen. So I redirect stderr to stdout, add the timestamp with awk und tee it to log file. But there is a problem to get the correct error code.
Here an example without logging:
$ less notexists.txt
notexists.txt: No such file or directory
$ echo $?
1
The error code is correct
Here the example with logging:
$ less notexists.txt 2>&1 | awk '{ print strftime("[%Y-%m-%d %H:%M:%S]"), $0; fflush(); }' | tee -a log.txt
[2017-10-23 17:19:59] notexists.txt: No such file or directory
$ echo ${PIPESTATUS[*]}
0 0 0
The error codes of all three sections are 0, but in the first section should be a 1. I think the problem could be the redirection of stderr.
Is there a solution to log stdout and stderr with timestamp to a log file and view it on screen and get the correct error code?
Is it possible to duplicate stderr instead of redirect it?
lesshaving something other than a terminal as its standard output; try{ less noexists.txt; echo $?; } | cat.