Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
709 views
Welcome To Ask or Share your Answers For Others

1 Answer

True cross-platform solution, works properly on Windows:

# Cross-platform way of finding an executable in the $PATH.
#
#   which('ruby') #=> /usr/bin/ruby
def which(cmd)
  exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
  ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
    exts.each do |ext|
      exe = File.join(path, "#{cmd}#{ext}")
      return exe if File.executable?(exe) && !File.directory?(exe)
    end
  end
  nil
end

This doesn't use host OS sniffing, and respects $PATHEXT which lists valid file extensions for executables on Windows.

Shelling out to which works on many systems but not all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...