Get the Absolute Location of the Current Script

May 20, 2009

Okay, It’s about time I document this, since I use it so often and work with enough languages that I have to keep looking it up!

When writing a script that needs to access files in or below its current directory, it’s a good idea to use paths relative to the location of the script itself, so that things continue to work regardless of where they live on the file system. The problem is that when a script is run, all paths are relative to the current working directory of the user who executed it, rather than the directory that the script actually lives in. To work around this, you can just prefix your paths with a variable containing the absolute location of the current script:

Bash:

            cwd=$(dirname $(readlink /proc/$$/fd/255))
            

PHP:

            $cwd = realpath(dirname(__FILE__))
            

Python:

            cwd = os.path.abspath(os.path.dirname(__file__))
            

Note that the above may not work when your program is “frozen” (e.g. compiled with py2exe).

Ruby

            cwd = File.expand_path(File.dirname(__FILE__))
            

Windows Shell:

            set CWD=%~dp0
            
blog comments powered by Disqus