I am trying to write everything that comes out of stdout and stderr to a log file and save the console. For this, I simply added: |& tee -a log_file.logto each team.
However, I also want to run a custom command if an error occurs during the script. To this I added the following to the beginning of the script: trap "echo Non-zero exit code detected" ERR.
The problem is using the pipe operator, the echo in the trap is no longer performed.
Script 1, without pipe:
$cat test.sh
#!/bin/bash
trap "echo Non-zero exit code detected!" ERR
function fail_please()
{
echo "Returning non-zero exit code!"
return 1
}
fail_please
Output 1:
$ ./test.sh
Returning non-zero exit code!
Non-zero exit code detected!
Script 2, with pipe:
$ cat test.sh
#!/bin/bash
trap "echo Non-zero exit code detected!" ERR
function fail_please()
{
echo "Returning non-zero exit code!"
return 1
}
fail_please |& tee log_file.log
Output 2:
$ ./test.sh
Returning non-zero exit code!
$ cat log_file.log
Returning non-zero exit code!
At output 2, the message "An unnecessary exit code has been detected!" Appears. gone, missing. Any idea why? Thank!