Can a Ruby script tell what directory it’s in?

35,358

Solution 1

For newer versions of Ruby, try:

  • __dir__

For older versions of Ruby (< 2.0), the script being run can be found using:

  • File.dirname(__FILE__) - relative path; or
  • File.expand_path(File.dirname(__FILE__)) - the absolute path.

Note: Using __dir__ will return the script path even after a call to Dir.chdir; whereas, using the older syntax may not return the path to the script.

Solution 2

Use __dir__

As of Ruby 2.0, __dir__ is the simplest way to get this. It

Returns the canonicalized absolute path of the directory of the file from which this method is called.

See the __dir__ documentation, and "Why is __FILE__ uppercase and __dir__ lowercase?".

Solution 3

use __dir__

File.dirname(__FILE__) is not a proper way to get directory where script is stored.

At start working directory and directory with script file is the same, but it may change.

For example:

Dir.chdir('..') do
    puts __dir__
    puts File.expand_path(File.dirname(__FILE__))
end

for script file stored in /Desktop/tmp running it will give output

/home/mateusz/Desktop/tmp
/home/mateusz/Desktop
Share:
35,358

Related videos on Youtube

java.is.for.desktop
Author by

java.is.for.desktop

Updated on December 01, 2021

Comments

  • java.is.for.desktop
    java.is.for.desktop over 2 years

    Inspired by "Getting the source directory of a Bash script from within", what's the Ruby way to do this?

  • java.is.for.desktop
    java.is.for.desktop over 14 years
    Thanks! Good for my Linux-specific general knowledge.
  • Matthew Flaschen
    Matthew Flaschen over 14 years
    That's the home directory, not the current working directory or the directory where the script is located.
  • Shadowfirebird
    Shadowfirebird over 14 years
    B*gger, lack of sleep will do that. I meant ENV["PWD"] of course. But ba's answer is way better.
  • michelson
    michelson over 14 years
    Isn't that simply the working directory of the process? I thought that the OP wanted the directory containing the script.
  • java.is.for.desktop
    java.is.for.desktop over 14 years
    No, the process could execute an external script from elsewhere.
  • SidOfc
    SidOfc over 6 years
    Well, aside from __dir__ being the correct answer, thanks for also linking to the uppercase-vs-lowercase difference, was my first question after finding it as well :)
  • Kapidis
    Kapidis almost 4 years
    The 'File.expand_path(File.dirname(FILE))' was useful in finding trhe absolute path
  • iBug
    iBug over 2 years
    This env var depends on the shell. It's nowhere near "reliable". E.g., services forked off systemd doesn't contain this variable at all.