Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the exit status for a command invoked with IO.popen?

Tags:

ruby

I am using IO.popen to execute a command and am capturing the output like so:

process = IO.popen("sudo -u service_user -i start_service.sh") do |io|
    while line = io.gets
      line.chomp!
      process_log_line(line)
    end
  end

How can I capture the exit status of *start_service.sh*?

like image 347
Jordan Dea-Mattson Avatar asked Jan 16 '13 02:01

Jordan Dea-Mattson


1 Answers

You can capture the exit status of a command invoked via IO.open() by referencing $? as long as you have closed the pipe at the end of your block.

In the example above, you would do:

  process = IO.popen("sudo -u service_user -i start_service.sh") do |io|
    while line = io.gets
      line.chomp!
      process_log_line(line)
    end
    io.close
    do_more_stuff if $?.to_i == 0 
  end

See Ruby Core Library entry for IO.popen for more information.

like image 110
Jordan Dea-Mattson Avatar answered Oct 05 '22 11:10

Jordan Dea-Mattson