views:

149

answers:

2

I'm writing some scripts in Ruby, and I need to interface with some non-Ruby code via shell commands. I know there are at least 6 different ways of executing shell commands from Ruby, unfortunately, none of these seem to stop execution when a shell command fails.

Basically, I'm looking for something that does the equivalent of:

set -o errexit

...in a Bash script. Ideally, the solution would raise an exception when the command fails (i.e., by checking for a non-zero return value), maybe with stderr as a message. This wouldn't be too hard to write, but it seems like this should exist already. Is there an option that I'm just not finding?

+1  A: 

You can use one of ruby's special variables. The $? (analogous to the same shell script var).

`ls`
if $?.to_s == "0"
  # Ok to go
else
  # Not ok
end

Almost every program sets this var to 0 if everything went fine.

tsenart
Why would you use `to_s` to compare with the string `0`? `if $? == 0`
glenn jackman
+2  A: 

Easiest way would be to create a new function (or redefine an existing one) to call system() and check the error code.

Something like:

old_sys = system

def system(...)
  old_system(...)
  if $? != 0 then raise :some_exception
end

This should do what you want.

Yeah, this was what I was thinking when I said "wouldn't be too hard to write", but it just seems like something that should have been solved already, you know? Thanks for the example.
Benjamin Oakes
Although, you'd want to `raise` instead of `throw`
glenn jackman
@glenn good catch, fixed.