Monday, January 21, 2013

What are the various ways you can run UNIX commands in Ruby?

Backticks (``) - Backticks (aka backquotes) runs the command in a sub-shell and returns the standard output from that command.

#!/usr/local/bin/ruby -w
today = `date`
puts today

System (Kernel.system) - This command runs in a subshell and returns true if the command ran successfully and false otherwise.

system "ls -1"

Exec (Kernel.exec) - It runs the given command by replacing the current process with the one created by the external command.

exec "ls -1"

spawn (available in Ruby v1.9. aka Kernel.spawn also available as Process.spawn) - It doesn‘t wait for end of the command but returns the pid of the sub-process. Therefore, you'll have to use Process.wait or Process.detach on the resulting pid.

pid = kernel.spawn ("ls -lA", {:chdir => "/home/ravi"})
Process.wait pid

%x operator - The operator makes it easy and readable to use quotes in a command.

#!/usr/bin/env ruby
list=%x[ls -1]
puts list

IO.popen - It is another way to run a command in a sub-process. It helps you control the connection to IO object between standard input and standard output in that the sub-process.

Open3.popen3 - The Ruby standard library includes the class Open3. It is easy to use and returns stdin, stdout and stderr.

Open4.popen4 - It is a Ruby Gem put together by Ara Howard. It operates similarly to open3 except that we can get the exit status from the program. It also returns a process id for the subshell and we can get the exit status from that waiting on that process.

No comments :