“which in ruby”: Checking if program exists in $PATH from ruby

后端 未结 16 1041
萌比男神i
萌比男神i 2020-12-07 12:15

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 commandlin

16条回答
  •  有刺的猬
    2020-12-07 12:42

    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.

提交回复
热议问题