"which in ruby": Checking if program exists in $PATH from ruby

Viewed 26997

my scripts rely heavily on external programs and scripts. I need to be sure that a program I need to call exists. Manually, I'd check this using 'which' in the commandline.

Is there an equivalent to File.exists? for things in $PATH?

(yes I guess I could parse %x[which scriptINeedToRun] but that's not super elegant.

Thanks! yannick


UPDATE: Here's the solution I retained:

 def command?(command)
       system("which #{ command} > /dev/null 2>&1")
 end

UPDATE 2: A few new answers have come in - at least some of these offer better solutions.

Update 3: The ptools gem has adds a "which" method to the File class.

15 Answers

Use find_executable method from mkmf which is included to stdlib.

require 'mkmf'

find_executable 'ruby'
#=> "/Users/narkoz/.rvm/rubies/ruby-2.0.0-p0/bin/ruby"

find_executable 'which-ruby'
#=> nil

You can access system environment variables with the ENV hash:

puts ENV['PATH']

It will return the PATH on your system. So if you want to know if program nmap exists, you can do this:

ENV['PATH'].split(':').each {|folder| puts File.exists?(folder+'/nmap')}

This will print true if file was found or false otherwise.

Not so much elegant but it works :).

def cmdExists?(c)
  system(c + " > /dev/null")
  return false if $?.exitstatus == 127
  true
end

Warning: This is NOT recommended, dangerous advice!

Related