Raise exception on command line failure?

I am writing some scripts in Ruby, and I need to interact with non-Ruby code using shell commands. I know that there are at least 6 different ways to execute shell commands from Ruby, but, unfortunately, none of them stops execution when a shell command fails.

Essentially, I'm looking for something that matches:

set -o errexit 

... in the Bash script. Ideally, the solution should throw an exception when the command fails (i.e., by checking for a non-zero return value), possibly with stderr as the message. It would not be too difficult to write, but it seems that it should already exist. Is there an option that I just can't find?

+6
source share
4 answers

The easiest way is to create a new function (or override an existing one) to call the system () and check the error code.

Sort of:

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

This should do what you want.

+9
source

You can use one of the special ruby โ€‹โ€‹variables. $? (similar 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.

+7
source

A tiny bit is simpler: you do not need to check $? w / system , and since the command that you run displays on stderr itself, you can usually just distinguish from zero, rather than throw an exception w / ugly stack trace:

 system("<command>") || exit(1) 

So you can take the next step and do:

 (system("<command 1>") && system("<command 2>") && system("<command 3>")) || exit(1) 

... which will short-circuit and fail on error (in addition to being difficult to read).

Ref: From Ruby 2.0 doc for system (although true for 1.8.7):

the system returns true if the command gives a zero exit status, false for a non-zero status.

http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-system

+7
source

Ruby 2.6 adds exception: argument :

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

Source: https://habr.com/ru/post/1300684/


All Articles