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
- backticks:
`command arg1 arg2`
- delimited form, e.g.
%x(command arg1 arg2)
(other delimiters available) kernel#system
method:system('command arg1 arg2')
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 sh's , bash'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
Post a Comment