How do I call shell commands from inside of a Ruby program?
(如何从Ruby程序内部调用Shell命令?)
(然后如何将这些命令的输出返回到Ruby?)
This explanation is based on a commented Ruby script from a friend of mine.
(该说明基于我的一个朋友的注释Ruby脚本 。)
(如果要改进脚本,请随时在链接上进行更新。)
First, note that when Ruby calls out to a shell, it typically calls /bin/sh , not Bash.
/bin/sh
(首先,请注意,当Ruby调用shell时,通常调用/bin/sh 而不是 Bash。)
(/bin/sh并非在所有系统上都支持某些Bash语法。)
Here are ways to execute a shell script:
(以下是执行Shell脚本的方法:)
cmd = "echo 'hi'" # Sample string that can be used
Kernel#` , commonly called backticks – `cmd`
Kernel#`
`cmd`
(Kernel#` ,通常称为反引号– `cmd`)
This is like many other languages, including Bash, PHP, and Perl.
(就像许多其他语言一样,包括Bash,PHP和Perl。)
Returns the result (ie standard output) of the shell command.
(返回shell命令的结果(即标准输出)。)
Docs: http://ruby-doc.org/core/Kernel.html#method-i-60
(文件: http : //ruby-doc.org/core/Kernel.html#method-i-60)
value = `echo 'hi'` value = `#{cmd}`
Built-in syntax, %x( cmd )
%x( cmd )
(内置语法%x( cmd ))
Following the x character is a delimiter, which can be any character.
x
(x字符后是分隔符,可以是任何字符。)
(
[
{
<
#{ ... }
(如果定界符是字符( , [ , {或< ,下次出现分隔符时,允许使用字符串插值#{ ... } 。)
Returns the result (ie standard output) of the shell command, just like the backticks.
(像反引号一样,返回shell命令的结果(即标准输出)。)
Docs: http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html
(文件: http : //www.ruby-doc.org/docs/ProgrammingRuby/html/language.html)
value = %x( echo 'hi' ) value = %x[ #{cmd} ]
Kernel#system
Executes the given command in a subshell.
(在子shell中执行给定命令。)
Returns true if the command was found and run successfully, false otherwise.
true
false
(如果找到命令并成功运行,则返回true ,否则返回false 。)
Docs: http://ruby-doc.org/core/Kernel.html#method-i-system
(文件: http : //ruby-doc.org/core/Kernel.html#method-i-system)
wasGood = system( "echo 'hi'" ) wasGood = system( cmd )
Kernel#exec
Replaces the current process by running the given external command.
(通过运行给定的外部命令来替换当前进程。)
Returns none, the current process is replaced and never continues.
(不返回任何值,当前进程将被替换且永远不会继续。)
Docs: http://ruby-doc.org/core/Kernel.html#method-i-exec
(文件: http : //ruby-doc.org/core/Kernel.html#method-i-exec)
exec( "echo 'hi'" ) exec( cmd ) # Note: this will never be reached because of the line above
Here's some extra advice: $?
$?
(这里有一些额外的建议: $?)
$CHILD_STATUS
system()
%x{}
(与$CHILD_STATUS相同,如果使用反引号, system()或%x{} ,则访问上次系统执行的命令的状态。)
exitstatus
pid
(然后,您可以访问exitstatus和pid属性:)
$?.exitstatus
For more reading see:
(有关更多阅读,请参阅:)
(http://www.elctech.com/blog/im-in-ur-commandline-executin-ma-commands)
(http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html)
(http://tech.natemurray.com/2007/03/ruby-shell-commands.html)
1.4m articles
1.4m replys
5 comments
57.0k users