Raise exception on shell command failure? Raise exception on shell command failure? ruby ruby

Raise exception on shell command failure?


Ruby 2.6 adds an exception: argument:

system('ctat nonexistent.txt', exception: true) # Errno::ENOENT (No such file or directory - ctat)


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 = systemdef system(...)  old_system(...)  if $? != 0 then raise :some_exceptionend

This should do what you want.


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

`ls`if $?.to_s == "0"  # Ok to goelse  # Not okend

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