shell-executer
Shell::Executer provides an easy and robust way to execute shell commands. The stdout and stderr data can be read completely after the execution or in chunks during the execution. If the data is processed in chunks this could be done by line or by char.
Command execution is done utilizing open4.
Download and Installation
You can download shell-executer from here or install it with the following command.
$ gem install shell-executer
License
You may use, copy and redistribute this library under the same terms as Ruby itself (see www.ruby-lang.org/en/LICENSE.txt).
Usage
require 'shell/executer.rb'
# execute and read standard output
Shell.execute('echo hello').stdout # => "hello\n"
# execute and read error output
Shell.execute('echo >&2 error').stderr # => "error\n"
# execute and check if the command exited with success
Shell.execute('ls /tmp').success? # => true
Shell.execute('ls /not_existing').success? # => false
# execute and process every line of output with block
Shell.execute('echo hello; echo world') {|stdout| print stdout }
# => "hello\n"
# => "world\n"
# execute and process every char of output with block
Shell.execute('echo 42', :mode => :chars) {|stdout| puts stdout }
# => "4\n"
# => "2\n"
# execute and process every line of stdout or stderr
Shell.execute('echo hello; echo >&2 error') do |stdout, stderr|
if stdout
print 'OUT> %s' % stdout
else
print 'ERR> %s' % stderr
end
end
# => "OUT> hello\n"
# => "ERR> error\n"
# execute and throw an exception if the process exited without success
begin
Shell.execute!('ls /not_existing')
rescue RuntimeError => e
print e. # <= prints stderr
end