LoginSignup
7
7

More than 5 years have passed since last update.

Rubyで指定したコマンドが存在するかを調べるには?

Posted at

cat, xargs, grep のような一部環境に無いコマンドがあるかを調べて分岐する時に使う。

util.rb
# 指定したコマンドが存在するか?
def exist_command?(command)
  begin
    Open3.capture3("type #{command}")[2].exited?
  rescue Errno::ENOENT
    false
  end
end

使い方。

use_exist_command.rb
# cat, grep, xargs コマンドの存在を確認
if exist_command?('cat') && exist_command?('grep') && exist_command?('xargs')
  system("cat /path/to/file | xargs grep keyword") # ばんばん使える!
else
  puts "Not found command..."
end
  • module Open3を使うことで、結果をコンソールに表示せずに実行結果を受け取ることが出来た
  • OS種類で判定するとcygwinが入ったWindows等が検出出来ないので直接コマンドを探す方がよい時が多い
  • typeコマンドが存在しない時、常にfalseになってしまうのはもう少し改善の余地がありそう(他のコマンドも試すなど)
7
7
6

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
7
7