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

后端 未结 16 1043
萌比男神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:52
    def command?(name)
      `which #{name}`
      $?.success?
    end
    

    Initially taken from hub, which used type -t instead of which though (and which failed for both zsh and bash for me).

    0 讨论(0)
  • 2020-12-07 12:52

    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!

    0 讨论(0)
  • 2020-12-07 12:53

    There was a GEM called which_rubythat was a pure-Ruby which implementation. It's no longer available.

    However, I found this pure-Ruby alternative implementation.

    0 讨论(0)
  • 2020-12-07 12:53

    On linux I use:

    exists = `which #{command}`.size.>(0)
    

    Unfortunately, which is not a POSIX command and so behaves differently on Mac, BSD, etc (i.e., throws an error if the command is not found). Maybe the ideal solution would be to use

    `command -v #{command}`.size.>(0)  # fails!: ruby can't access built-in functions
    

    But this fails because ruby seems to not be capable of accessing built-in functions. But command -v would be the POSIX way to do this.

    0 讨论(0)
提交回复
热议问题