0

I have a script as below:

function dbgtrap {
echo "badvar is $badvar" 
}

badvar=0

function some_func {
    badvar=1
    badvar=2
    badvar=3
}

set -o functrace

trap dbgtrap DEBUG
    some_func
trap - DEBUG    # turn off the DEBUG trap

After I source the script, I got the output:

badvar is 0
badvar is 0
badvar is 0
badvar is 1
badvar is 2
badvar is 3

I was expecting sth like:

badvar is 0
badvar is 1
badvar is 2
badvar is 3

Where do the first two lines of the output come from?

2

The trap is invoked after every command line once set. As shown by using the TRACE output below:

+ badvar=0
+ set -o functrace
+ trap dbgtrap DEBUG
++ dbgtrap
++ echo 'badvar is 0'
badvar is 0
+ some_func
++ dbgtrap
++ echo 'badvar is 0'
badvar is 0
++ dbgtrap
++ echo 'badvar is 0'
badvar is 0
+ badvar=1
++ dbgtrap
++ echo 'badvar is 1'
badvar is 1
+ badvar=2
++ dbgtrap
++ echo 'badvar is 2'
badvar is 2
+ badvar=3
++ dbgtrap
++ echo 'badvar is 3'
badvar is 3
+ trap - DEBUG

IIRC shell invokes the trap at end of processing hence the 3 lines of output before the function call output of badvar values.

  • 1
    after every command, and (per bash manual) "before the first command executes in a shell function", which covers the third copy of "badvar is 0" – user4556274 Jun 10 '19 at 14:58
  • can you please tell me what the "++" sign means in this TRACE output? – Jack Chen Jun 10 '19 at 15:07
  • 1
    man bash: The first character of PS4 is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is ''+ ''. – user4556274 Jun 10 '19 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.