LoginSignup
5
5

More than 5 years have passed since last update.

Rubyでコマンドの存在をチェックする

Posted at

参考 : Bash - コマンドの存在チェックはwhichよりhashの方が良いかも→いやtypeが最強 - Qiita

なるほどう。

TL;DR

def exists?(command)
  !`type #{command}`.empty?
end

ユーザ入力を直接渡すとかしないように。

検証

[1] pry(main)> `type wget`
=> "wget is /usr/local/bin/wget\n"
[2] pry(main)> `type hoge`
/usr/bin/type: line 4: type: hoge: not found
=> ""
[3] pry(main)> `type wget`.empty?
=> false
[4] pry(main)> `type hoge`.empty?
/usr/bin/type: line 4: type: hoge: not found
=> true
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5