Peter Marklund

Peter Marklund's Home


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.

5 comment(s)


Brad Phelan said 2010-09-30 07:47:

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

Herman Munster said 2010-06-29 11:55:

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

Herman Munster said 2010-06-29 11:17:

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

Duane Johnson said 2008-07-26 18:23:

Thanks! That was just what I was looking for.