How to get Ruby script to fail when shelled-out command returns with non-zero exit code? -


in ruby script, there various ways call system commands / command lines

  1. backticks: `command arg1 arg2`
  2. delimited form, e.g. %x(command arg1 arg2) (other delimiters available)
  3. kernel#system method: system('command arg1 arg2')
  4. kernel#exec method: exec('command arg1 arg2')

if want ruby script fail (with exception) when called command fails (with non-zero exit code) can either check exit code in special variable $? first 2 variants:

`command arg1 arg2` fail unless $? == 0 

or

%x,command arg1 arg2, fail unless $? == 0 

if i'm fine command's standard output going ruby script's standard output (and am), can use variant 3 , check return value:

unless system('command arg1 arg2')   fail end 

if don't care ability rescue exception nor stacktrace printing behavior of unrescued exceptions, can of course use exit(1) or in first 2 variants exit($?) in place of fail.

if further execution of command last thing ruby script should do, when command succeeds (exit code 0), can use fourth variant:

exec('command arg1 arg2') 

this replace ruby process new process created invoking command, effect caller of ruby script same: sees non-zero exit code if called command caused non-zero exit code.

i conciseness of fourth variant, if executing command isn't last thing in case succeeds, can unfortunately not use it. conditional fail or exit invocations of other variants unclean in comparison , in 1 usecase of mine more not violate single level of abstraction , single responsibility principles.

i of course write wrapper function of first 3 approaches make usage concise, seems such fundamental modus operandi, i wondered whether ruby has built in ... utility function use instead of wrapper of own, or mechanism changes behavior of 1 or several of command invocation methods cause error or non-zero exit when command fails, analogous 's , 's option set -e.

as far know there no built-in way this, can behavior want little metaprogramming magic

def set_exit enable   if enable     define_method :system |*args|       kernel.system *args       exit $?.exitstatus unless $?.success?     end   else     define_method :system, kernel.instance_method(:system)   end end  set_exit true # ... # failed system calls here cause script exit # ... set_exit false # system normal 

this works redefining system object, while explicitly using kernel.system when built-in behavior needed.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -