How to capture the output of a command without it displaying in stdout

185 views Asked by At

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.

1

There are 1 answers

8
akuhn On BEST ANSWER

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