Peter Marklund

Peter Marklund's Home

Mon June 16, 2008
Programming

Ruby Gotcha: Symlinked Scripts and File.dirname(__FILE__)

If you have a Ruby script say in ~/src/ruby/my_script that you are symlinking to from ~/bin/my_script, then invoking File.dirname(__FILE__) in that script will yield the directory of the symlink not the directory of the script file. If you want the directory of the script file you can do this instead:

THIS_FILE = File.symlink?(__FILE__) ? File.readlink(__FILE__) : __FILE__

THIS_FILE will contain the path to the script file instead of the path to the symlink. This is valuable if say you want to require some Ruby library from your script and you are using a relative path.

Comments

Duane Johnson said over 6 years ago:

Thanks! That was just what I was looking for.

--------------------------------------------------------------------------------

Herman Munster said over 4 years ago:

Thanks a lot, this is a good help.

If the script is called directly, not by a symlink, then "__FILE__" only gives a relative path like "./script.rb".
Therefore I've exchanged the rightmost "__FILE__" by "File.expand_path(File.dirname(__FILE__))", which leads to:

THIS_FILE = File.symlink?(__FILE__) ? File.readlink(__FILE__) : File.expand_path(File.dirname(__FILE__))

--------------------------------------------------------------------------------

Herman Munster said over 4 years ago:

to require files located in the script's directory, I now use this:
$: << File.expand_path(File.dirname( File.symlink?(__FILE__) ? File.readlink(__FILE__) : __FILE__ ))

--------------------------------------------------------------------------------

Brad Phelan said over 4 years ago:

First hit when I searched for this problem under google. Ta for that.

--------------------------------------------------------------------------------