How to get path of current script?

tcl
vasili111 picture vasili111 · Apr 25, 2014 · Viewed 19.5k times · Source

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

Answer

Donal Fellows picture Donal Fellows · Apr 25, 2014

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.)