command_utils

Build Status Inline docs Gem Version GitHub issues GitHub license Downloads

Description

This gem provides a simple interface to execute external commands. You can capture both stdout / stderr, process it, and be safe that if command has not exited with 0, you will get an exception.

Install

gem install command_utils

This gem uses Semantic Versioning, so you should add to your .gemspec something like:

  s.add_runtime_dependency 'command_utils', '~> 0.4', '>= 0.4.1'

Examples

First, require it:

require 'command_utils'

Read each line

command = 'echo -n stdout message ; echo -n stderr message 1>&2'
CommandUtils.each_line(command) do |stream, data|
  puts "#{stream}: #{data}"
end

Send output to logger

require 'logger'
command = 'echo -n stdout message ; echo -n stderr message 1>&2'
CommandUtils.logger_exec(
  command,
  logger: Logger.new(STDOUT),
  stdout_level: :info,
  stderr_level: :error,
  stdout_prefix: 'This was output to stdout: ',
  stderr_prefix: 'This was output to stderr: ',
  )

Raises unless 0 exit

command = 'echo -n stdout message ; echo -n stderr message 1>&2 ; exit 3'
begin
  CommandUtils.each_output(command) do |stream, data|
    puts "#{stream}: #{data}"
  end
rescue
  $stderr.puts "Raised #{$!.class}: #{$!}"
end