Version 14 of Determining the Applications Root Directory

Updated 2005-02-16 11:39:04 by cl

I refactored this page to eliminate some of the noise. Original contributions from Marty Backe & Stephen Hill. Marty Backe - 23 Nov 2004


An application might be written that sources needed files, makes use of images files, etc. All the files are relative to the physical location of the actual program.

Problem How do you determine the directory (without hardcoding it in the program) that contains your executable? This isn't as easy as you might first think. What if the executable is executed via an alias (UNIX) or shortcut (Windows). Or perhaps a symbolic link (UNIX) to the executable is used.

Solution This bit of code will do the trick. The while loop is used to resolve multiple symbolic links.

 set originalPath [pwd]
 set scriptPath   $::argv0
 set workingPath  [file dirname $::argv0]
 while {![catch {file readlink $scriptPath} result]} {
     cd $workingPath
     set scriptPath  [file join [pwd] $result]
     set workingPath [file dirname $scriptPath]
 }
 cd [file dirname $scriptPath]
 set scriptPath [pwd]
 cd $originalPath

See Making a Path Absolute for a related discussion


If you are using a Starkit, the root directory is contained in the starkit::topdir variable

    package require starkit
    puts stderr "root directory = $starkit::topdir"

FW: Of course, if you're satisfied with it only working if the application is invoked directly, then you can just invoke this code to retrieve the application root:

  file dirname [info script]

US: See also: Techniques for reading and writing application configuration files


Category deployment