Question

I am trying to check if system command exists with following code:

require 'open3'

Open3.popen3('non-existing command') do |stdin, stdout, stderr, thread|
  exit_error = stderr.readlines
  if exit_error["No such file or directory"]
    puts "command not found"
  end
end

However it simply crashes with following error message and doesn't proceed:

/home/pavel/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/open3.rb:211:in `spawn': No such file or directory - non-existing (Errno::ENOENT)

Why and how to fix it?

Was it helpful?

Solution

Seems that Open3.popen3 raises a Errno::ENOENT exception if it doesn't find the command; so you just have to rescue from that exception:

require 'open3'

begin
  Open3.popen3('non-existing command') do |stdin, stdout, stderr, thread|
  end
rescue Errno::ENOENT
  puts "command not found"
end

#=> outputs "command not found"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top