How to get path of current script?
Asked Answered
E

5

19

Sometimes its needed to get current path of a script. What are the ways to do that?

Emissive answered 25/4, 2014 at 6:9 Comment(0)
S
29

While a script is being evaluated (but not necessarily while its procedures are being called) the current script name (strictly, whatever was passed to source or the C API equivalent, Tcl_EvalFile() and related) is the result of info script; it's highly advisable to normalise that to an absolute pathname so that any calls to cd don't change the interpretation.

Scripts that need the information tend to put something like this inside themselves:

# This is a *good* use of [variable]…
variable myLocation [file normalize [info script]]

They can then retrieve the value (or things derived from it) easily:

proc getResourceDirectory {} {
    variable myLocation
    return [file dirname $myLocation]
}

The other common locations are:

  • $::argv0 which is the “main” script (and you're evaluating the main script if it's equal to info script)
  • [info nameofexecutable] which is the Tcl interpreter program itself (typically the argv[0] at the C level)
  • [info library] which is where Tcl's own library scripts are located
  • $::tcl_pkgPath which is a Tcl list of directories where packages are installed
  • $::auto_path which is a Tcl list of directories where scripts are searched for (including packages! The package path is used to initialise this.)
Sessler answered 25/4, 2014 at 7:46 Comment(1)
A problem with this approach is that in nested scripts (where one script calls another) the [info script] call may refer to the currently executing script, and not the location of this call. Here is a way around that: #3839091Globate
E
15

The best way I found to do that:

set script_path [ file dirname [ file normalize [ info script ] ] ]
puts $script_path
Emissive answered 25/4, 2014 at 6:9 Comment(0)
C
1

You may also try like this:

file normalize $argv0
file normalize [info nameofexecutable]

to get fully normalized name

Courier answered 25/4, 2014 at 6:12 Comment(0)
S
1

You might have a look at http://wiki.tcl.tk/1710. The solution there also takes care of possible (multiple) symbolic links and points to the physical root location of the script.

Superfecundation answered 25/4, 2014 at 6:30 Comment(1)
This is more of a comment than an answer.Aleuromancy
L
1

In case it does not work with "info script", you can do

regsub {/[a-zA-Z0-9_]+$} $argv0 {} path
do $path/other_script_on_the_same_path_as_this.tcl

Now you will have the path of the current script on the variable $path.

Laurynlausanne answered 21/6, 2021 at 5:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.