Bash Shell – Use of Declare with Option -t

bashfunctionshell-scripttrap:

If you call the command help declare. You will see the following information:

-t NAME :  to make NAMEs have the `trace' attribute

Is there any example that demonstrates the use of this option. I thought that this plays the same role as that of the command set -o functrace except that it only applies to the arguments instead of all functions.

The motivation of this question is that I want a function foo to inherits a trap. So I tried declare -t foo but it did not work.

I can certainly use set -o functrace to make all functions to inherit a trap, but there are circumstances when I want only one or two functions to inherit a trap.

Here is the script:

function foo {
    var=1
    var=2
    var=3
}

declare -t foo

var=0

trap 'echo var is $var' DEBUG
    foo
trap - DEBUG    # turn off the DEBUG trap

Here is the output of the script:

var is 0
var is 3

I was expecting to get something like:

var is 0
var is 1
var is 2
var is 3

Best Answer

declare -t foo sets the trace attribute on the variable foo (which has no special effect anyway). You need to use -f to set it on the function:

declare -ft foo

With your script modified to use -f, I get the following output (explanation in comments):

var is 0 # foo called
var is 0 # before the first command in function is run
var is 0 # var=1
var is 1 # var=2
var is 2 # var=3
var is 3 # trap ...
Related Question