问题

如何从Ruby程序中调用shell命令?我如何从这些命令的输出返回到Ruby?



解决方法

此解释是基于我的朋友的 Ruby脚本.如果您想改进脚本,请随时在链接中进行更新.

首先,请注意,当Ruby调用shell时,通常会调用 / bin / sh ,不是 Bash. / bin / sh 在所有系统上不支持某些Bash语法.

以下是执行shell脚本的方法:

cmd = "echo 'hi'" # Sample string that can be used
  1. Kernel#` , commonly called backticks – `cmd`

    This is like many other languages, including Bash, PHP, and Perl.

    Returns the result of the shell command.

    Docs: http://ruby-doc.org/core/Kernel.html#method-i-60

    value = `echo 'hi'`
    value = `#{cmd}`
    
  2. Built-in syntax, %x( cmd )

    Following the x character is a delimiter, which can be any character. If the delimiter is one of the characters (, [, {, or <, the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character. String interpolation #{ ... } is allowed.

    Returns the result of the shell command, just like the backticks.

    Docs: http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html

    value = %x( echo 'hi' )
    value = %x[ #{cmd} ]
    
  3. Kernel#system

    Executes the given command in a subshell.

    Returns true if the command was found and ran successfully, false otherwise.

    Docs: http://ruby-doc.org/core/Kernel.html#method-i-system

    wasGood = system( "echo 'hi'" )
    wasGood = system( cmd )
    
  4. 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

    exec( "echo 'hi'" )
    exec( cmd ) # Note: this will never be reached because of the line above
    

这里有一些额外的建议: $? $ CHILD_STATUS 相同,访问上次系统执行命令的状态.或%x {} . 然后,您可以访问 exitstatus pid 属性:

$?.exitstatus

有关详情,请参阅:




相关问题推荐