Saari Development

Ali Rizvi's Technical Blog as a Professional Software Development Engineer

Ruby: Finding the absolute path of running script

leave a comment »

I needed to use the full/absolute path of the script/program to a library for access control. I had not done something like this before so here is my trail of discovery:


I started with $0, which in ruby is one of those magic variables that contain the name of the program that was executed from the command line.

The problem with $0 is that it does not necessary have the absolute path, it has whatever the user used which could be relative or absolute.


Then I found __FILE__ which was not exactly what I was looking for as it would give you the file name of the current file so when executing library routine it would be the name of the library file not the original executable file that the user ran.


After some research I found File.expand_path which essentially did the trick if you use it with $0. So File.expand_path $0 would give you the absolute path of the calling program.

On a parallel note I found also but that require you to require ‘pathname’ and also it resolved a symbolic link to real path which was not desired in my case.


One caveat with File.expand_path which an experienced rubyist pointed out that if a script does a Dir.chdir then File.expand_path would not work as it essentially prepends the cwd (current working directory) to $0 but even the fellow rubyist couldn’t think of a better way to do this so File.expand_path was my eventual solution and it works!


Written by imsaar

November 7, 2006 at 4:56 am

Posted in general

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: