Drektz
Drektz

Reputation: 95

How to print full path of a file being sourced?

let say there is a file a/b/c/d.tcl and it should print its full path when being sourced.

source d.tcl

And the output should be

a/b/c/d.tcl

How to do this? Is there any tcl variable which stores the full path info of the file being sourced?

Upvotes: 0

Views: 717

Answers (1)

Schelte Bron
Schelte Bron

Reputation: 4813

The info script command returns the file that is currently evaluated. Combine that with file normalize to get the full path:

puts [file normalize [info script]]

Beware that info script is only valid while the file is evaluated. Calling info script from procs that are defined by the script, but are evaluated later in response to an event will not produce the name of the file that defined the proc.

You sometimes see the claim that info script cannot be used in a proc. That is incorrect. It can be used in a proc, but it only produces a useful result if that proc is called directly while evaluating the script.

Example:

proc foo {} {
    puts [file normalize [info script]]
}

# This works fine:
foo

# This should not be trusted to produce the expected result:
after 5000 foo

To make that last command work, you would have to store the result of info script in a variable, and use that in your proc.

Upvotes: 1

Related Questions