I would like to create a shell-script like pipeline using command line commands in ru开发者_StackOverflowby. So I have a few steps in the pipeline, each step is a command line like commands (using a particular tool and the usual input and output files, like run xtool -i xx -o xxx).
Thanks in advance
Mark
You can run external programs by quoting with backticks or using %x:
x = `echo "hello"`
y = %x{echo "hello"}
You can look at the last process through $?
:
`rm an_existing_file`
$?.exitstatus # now: o
`rm missing_file`
$?.exitstatus # now: 1
If you need to do anything more complex, look at the Ruby Process Docs.
Hard to know what you are asking, but if you want to write a Ruby command-line app that can be used in a pipeline on the command line, but also possibly use command-line arguments, you can do this:
require 'optparse'
input = STDIN
output = STDOUT
option_parser = OptionParser.new do |opts|
options.on("-i FILE","Input file (defaults to stdin)") do |filename|
input = File.new(filename)
end
options.on("-o FILE","Output file (defaults to stdout)") do |filename|
output = File.new(filename,'w')
end
end
option_parser.parse!
input.readlines.each do |line|
# do something with line
output.puts "Some awesome output"
end
output.close # NOTE, this must be the last line of your program since
# you are possibly closing the standard output
You also have sh
and system
kernel methods. You can write your own shell script and invoke it using system('yourscript.sh')
.
system
returns true if the command gives zero exit status, false otherwise.
精彩评论