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

后端 未结 16 1107
萌比男神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: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.

提交回复
热议问题