【问题标题】:How can I retrieve the output of my command when using rake sh?使用 rake sh 时如何检索命令的输出?
【发布时间】:2009-09-17 23:41:14
【问题描述】:

我正在使用 sh 运行命令,需要读取该命令的输出。例如

sh "whoami"

但 sh 似乎只返回 true 而不是包含 whoami 命令输出的字符串。有谁知道解决办法吗?

【问题讨论】:

    标签: ruby rake


    【解决方案1】:

    有几种方法:

    output = `whoami`
    
    #or
    
    output = %x[whoami]
    
    # or using 'system' but in case of errors it's gonna return false
    
    output = system "whoami"
    

    【讨论】:

    • 感谢您提及“system "whoami"'——我正在寻找一种方法来抑制 'sh "diff a b"' 产生的命令和 'system "diff a b"' 就行了。
    【解决方案2】:

    只需使用反引号来执行语句:

    output = `whoami`
    

    结果将在“输出”变量中。

    【讨论】:

      【解决方案3】:

      我不确定如何让其他方法因错误而失败,所以我选择了重定向:

      sh "mysql --verbose #{connection_options} < #{sql_file} > #{sql_file_output_file}" do |ok, status|
        ok or fail "mysql file failed [#{sql_file}"
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-16
        • 1970-01-01
        • 1970-01-01
        • 2012-09-30
        • 2017-05-01
        • 1970-01-01
        • 2021-10-08
        • 2017-10-07
        相关资源
        最近更新 更多