Ruby: return nonzero exit status

Kei picture Kei · Jun 17, 2015 · Viewed 6.9k times · Source

I would like my Ruby script to return any non-zero exit status upon a certain condition. The exit status itself does not matter as long as it is not zero. I tested out how it's done:

test_exit.rb:

exit 4

test_exit_wrap.rb:

system("ruby test_exit.rb")
puts $?.exitstatus

cmd:

> ruby test_exit_wrap.rb
4

This is wonderful, because it's exactly what I want. Then I tried to replicate that in my project.

pullrequest.rb:

results = [install_result.class, clicks_result.class, event_result.class, tuples_result.class, match_result.class]

if results.include? NilClass 
    puts "result included nil"
    exit 4
end

rakefile.rb:

command = "irb #{@script} #{@app_id} #{start_date} #{end_date} #{start_time} #{end_time} #{@timezone} #{@database}"
system("#{command}")
puts $?.exitstatus

if $?.exitstatus != 0
    puts "!!!!!!!!!!!!!!!!!!!!!! FAILED JOB !!!!!!!!!!!!!!!!!!!!!!!!!!"
    @backjob_queue << fail
end

cmd:

  pullkochava.rb(main):032:1>  
  result included nil
  => nil
  pullrequest.rb(main):032:0>
  0

(Clipping these out, of course, hope it still makes sense; also @script is equal to pullrequest.rb, I've double checked) We can see that the if results.include? block is definitely executed, but the exit 4 seems to be lost. The 0 comes from the puts $?.exitstatus, and I can never get it to return anything but 0. I have tried raising errors, different exit codes, and abort. Abort does return a nonzero exit code; however it also aborts the rake. It will puts FAILED JOB but the rakefile doesn't get to save the @backjob_queue to my database.

Am I missing something? How can I return a nonzero exit status that won't abort the rake?

Answer

Kei picture Kei · Jun 17, 2015

I realized my error right away, but in case anyone else ever needs this answer:

your system command should be "ruby blahblahblah.rb" not "irb blahblahblah.rb". Both will run code but irb will return exit status 0 unless you abort.