Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing "command not found" errors from Ruby's backticks?

Is there a way to capture a "command not found" error in a Ruby script? For instance, given:

output = `foo`

How do I trap the situation where foo isn't installed? I expected that I could rescue an exception, but this doesn't seem to work on 1.8.7. Is there a different way of calling the subprocess that will do what I want? Or is there a different approach?

Update

My apologies, I forgot to mention a hidden requirement: I would prefer that the interpreter doesn't leak the command line to the user (it can contain sensitive data), hence why the exception catching method is preferred. Apologies again for leaving this out the first time.

like image 407
kfb Avatar asked Jan 24 '11 15:01

kfb


1 Answers

Use the return code!

irb(main):001:0> `date`
=> "Mo 24. Jan 16:07:15 CET 2011\n"
irb(main):002:0> $?
=> #<Process::Status: pid=11556,exited(0)>
irb(main):003:0> $?.to_i
=> 0
irb(main):004:0> `foo`
(irb):4: command not found: foo
=> ""
irb(main):005:0> $?.to_i
=> 32512

http://corelib.rubyonrails.org/classes/Process/Status.html

Redirecting STDERR to STDOUT will give you the output as return value instead of bloating it just out:

irb(main):010:0> `foo 2>&1`
=> "sh: foo: not found\n"
irb(main):011:0> $?.to_i
=> 32512
like image 108
Lennart Koopmann Avatar answered Nov 06 '22 15:11

Lennart Koopmann