Why is the DEBUG trap executed more times than expected?

Clash Royale CLAN TAG#URR8PPPWhy is the DEBUG trap executed more times than expected?
The following code triggers the debug trap 3 times. I am however expecting only 2 executions - one for foo, the second for echo hello:
foo
echo hello
foo() {
echo hello
}
set -T
trap 'echo oops' DEBUG
foo
Output:
oops
oops
oops
hello
Expected output:
oops
oops
hello
Bash versions tested:
Bash
GNU bash, version 4.3.30(1)-release (x86_64-unknown-linux-gnu)
GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)
GNU bash, version 5.0.0(1)-alpha (x86_64-pc-linux-gnu)
I am pretty sure I just misunderstood the manual and that I am missing something really simple/obvious here.
1 Answer
1
I assume you understand that DEBUG trap enables running the command before every other command and set -T enables the trap to all sub-shells and functions also. So once you set the trap you have three executions happening.
DEBUG
set -T
trap
foo
trap
echo oops
trap
echo
trap
echo
trap
hello
trap
See the sequence when ran from the debug mode
$ bash -x script.sh
+ set -T
+ trap 'echo oops' DEBUG
++ echo oops # <--- triggered by call to 'foo'
oops
+ foo
++ echo oops # <--- triggered by call to 'echo oops' inside trap definition
oops
++ echo oops # <--- result of the actual command to be run
oops
+ echo hello # <--- result of the function call 'foo'
hello
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.