4

I don't understand t and f parameters on declare command exactly why and how they are used. Would you please give me a few simple illustrations?

2
  • Parameters to what? Commented Jul 29, 2019 at 17:37
  • declare command @ilkkachu Commented Jul 29, 2019 at 17:39

1 Answer 1

5

The trace attribute makes the function in question inherit the DEBUG and RETURN traps. -f just means that the argument to declare is a function, and not a variable.

Bash's manual says this about functions:

All other aspects of the shell execution environment are identical between a function and its caller with these exceptions: the DEBUG and RETURN traps are not inherited unless the function has been given the trace attribute

And the description of declare:

-t Give each name the trace attribute. Traced functions inherit the DEBUG and RETURN traps from the calling shell. The trace attribute has no special meaning for variables.

Here's what happens with a function without the trace attribute:

$ f() { echo a; echo b; }
$ trap 'echo DEBUG: $BASH_COMMAND' DEBUG
$ f
DEBUG: f
a             
b             

And here's what happens when the function is given the trace attribute.

$ declare -f -t f
DEBUG: declare -f -t f
$ f
DEBUG: f      
DEBUG: f
DEBUG: echo a 
a      
DEBUG: echo b 
b             

(I have no idea why the function call shows up twice in the trap.)

2
  • 1
    from the trap entry in the bash(1) manpage (emphasis mine): " If a sigspec is DEBUG, the command arg is executed before every simple command, for command, case command, select command, every arithmetic for command, and before the first command executes in a shell function" Commented Jul 29, 2019 at 19:30
  • if you want to make the difference between the two, you could use the FUNCNAME array, as in my kludge here. Better ideas are welcome ;-) Commented Jul 29, 2019 at 19:34

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.