带选项 -t 的声明有什么用

Jac*_*hen 5 bash shell-script function trap

如果调用命令help declare. 您将看到以下信息:

-t NAME :  to make NAMEs have the `trace' attribute
Run Code Online (Sandbox Code Playgroud)

是否有任何示例演示此选项的使用。我认为这与命令的作用相同,set -o functrace只是它仅适用于参数而不是所有函数。

这个问题的动机是我想要一个函数 foo 继承一个陷阱。所以我试过了,declare -t foo但没有用。

我当然可以使用set -o functrace让所有函数都继承一个陷阱,但有些情况下我只希望一两个函数继承一个陷阱。

这是脚本:

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
Run Code Online (Sandbox Code Playgroud)

这是脚本的输出:

var is 0
var is 3
Run Code Online (Sandbox Code Playgroud)

我期待得到类似的东西:

var is 0
var is 1
var is 2
var is 3
Run Code Online (Sandbox Code Playgroud)

mur*_*uru 10

declare -t foo变量 上设置跟踪属性foo(无论如何都没有特殊效果)。您需要使用-f将其设置在函数上:

declare -ft foo
Run Code Online (Sandbox Code Playgroud)

将您的脚本修改为 use 后-f,我得到以下输出(注释中的解释):

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 ...
Run Code Online (Sandbox Code Playgroud)