Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture output of shell command, line by line, into an array

I want to capture the total number of rubocop offenses to determine whether my codebase is getting better or worse. I have almost no experience with ruby scripting.

This is my script so far:

#!/usr/bin/env ruby
#script/code_coverage

var = `rubocop ../ -f fuubar -o ../coverage/rubocop_results.txt -f offenses`
puts var

So I ./rails-app/script/code_coverage and my terminal displays

...
--
6844  Total

When I var.inspect I get a long string. I want to either read the output of rubocop ../ -f ... line by line (preferred) or capture each line of output into an array.

I would like to be able to do something like this:

var.each |line| do
  if line.contains('total')
    ...
    total = ...
end

Is this possible? I guess this would be similar to writing the output to a file and and then reading the file in line by line.

like image 889
Eric Francis Avatar asked Oct 29 '25 16:10

Eric Francis


2 Answers

If you want to keep it simple, you can simply split your var string.

var = `rubocop ../ -f fuubar -o ../coverage/rubocop_results.txt -f offenses`.split("\n")

Then you can iterate on var like you wanted to.

like image 100
Anuj Biyani Avatar answered Oct 31 '25 08:10

Anuj Biyani


use open3 library of ruby. Open3 grants you access to stdin, stdout, stderr and a thread to wait the child process when running another program. You can specify various attributes, redirections, current directory, etc., of the program as Process.spawn.

http://blog.bigbinary.com/2012/10/18/backtick-system-exec-in-ruby.html

require 'open3'


# Run lynx on this file.
cmd = "lynx -crawl -dump /data/feed/#{file_name}.html  > /data/feed/#{file_name}"
Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr|
   cmdout = stdout.read
   $logger.debug "stdout is:" + stdout.read
   $logger.debug "stderr is:" + stderr.read
end
like image 20
Sarvesh Avatar answered Oct 31 '25 06:10

Sarvesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!