2

How can I capture the output of a command and check for what it says without the command displaying in stdout? For example:

  def update!
      `git pull origin master`
      if $?.exitstatus > 0
        puts 'Failed to update'
      elsif $?.success?
        puts 'Upgraded successfully'
      else
        puts 'Already up to date'
      end
    end

How can I capture the output of this in order to check whether the command says up-to date, an error occurs, or successfully updates? Is there a way to write the output to a file instead of to the console?


Update for answer:

def update!
  update_status = `git pull origin master 2>&1`
  if $?.exitstatus > 0
    puts 'error'
  elsif update_status =~ /Already up-to date/
    puts 'same version as origin master'
  else
    puts 'updated'
  end
end

The output for this will always be:

[06:44:29 INFO] Updating to newest version..
updated

Even if the version is the same as the origin. What I would like to do, if possible, is save the stdout of the command to a file and read from that file to discover if the program was updated or not. I think that would be the easiest way to go about doing this.

User9123
  • 515
  • 2
  • 6
  • 14
  • Do you want to write tests for your method? – Sagar Pandya Dec 22 '16 at 01:55
  • @sagarpandya82 No, I'm trying to get a update method for a program I have written and want to capture the output of git itself. I just don't know if it's possible to write the output to a file or not – User9123 Dec 22 '16 at 01:57

1 Answers1

1

You can assign the output of the command to a string.

Use 2>&1 to redirect stderr to stdout and thus capture all the output.

str = `git pull origin master 2>&1`
if $?.exitstatus > 0
  ...
elsif str =~ /up-to-date/
  ...
else
  ...
end
akuhn
  • 27,477
  • 2
  • 76
  • 91