There are various ways in Ruby script to invoke system commands / command lines
- backticks:
`command arg1 arg2` - eg.
%x(command arg1 arg2) (other delimiters available) Kernel#system method: system('command arg1 arg2')Kernel#exec method: exec('command arg1 arg2')
If I want the Ruby script to fail (with an exception) when the called command fails (with a non-zero exit code), can I either check the exit code in the special variable $? for the first two options:
`command arg1 arg2` fail unless $? == 0
or
%x,command arg1 arg2, fail unless $? == 0
If everything is fine with the output of the standard command that goes to the standard output of the Ruby script (and I am), I can use option 3 and check its return value:
unless system('command arg1 arg2') fail end
If I donβt care about the possibility of saving the exception or how to print using the stitch of unsuccessful exceptions, I can of course use exit(1) or the first two options exit($?) Instead of fail .
If further execution of the command is the last thing the Ruby script should do, even when the command succeeds (exit code 0 ), I can use the fourth option:
exec('command arg1 arg2')
This will replace the Ruby process with the new process created when the command was called, but the effect for the calling Ruby script user will be the same: it will see a non-zero exit code exactly if the called command called a non-zero exit code.
I really like the brevity of the fourth option, but if executing a command is not the last thing to do if it succeeds, I, unfortunately, cannot use it. Conditional fail or exit calls of other options look very unclean in comparison and in one of my accounts most often do not violate a single level of abstraction and principles of a single responsibility.
I could, of course, easily write a wrapper function for any of the first three approaches, so that their use would look just as concise, but since it looks like such a fundamental modus operandi , I wondered if Ruby had something like that built in in ... whether it is a utility function that I could use instead of my own shell or a mechanism that changes the behavior of one or more methods of calling commands to cause an error or non-zero exit when a command fails, it is similar to sh and bash for set -e .