【问题标题】:How to execute shell command in Groovy and get the return code $?如何在 Groovy 中执行 shell 命令并获取返回码 $?
【发布时间】:2019-04-12 15:41:16
【问题描述】:

我无法通过在 Groovy 中执行 shell 脚本获得返回码(不是输出或错误)。

对于我尝试的所有方法,它要么要求我转义,要么只打印 $?而不是给我 1 或 0。

groovy: 75: 美元符号后面的非法字符串主体字符; 解决方案:要么转义文字美元符号“\$5”,要么将值表达式“${5}”括起来@第 75 行,第 24 列。

以下是我尝试过的解决方案,都不起作用。

println "../src/check_job_log.s ${it}.log".execute().text
println "Check log ${it}.log completed"

//assert ("echo \$?".execute().text == "1")
//output = """echo $?""".execute().text
println(['echo', '$?'].execute().text)

// below is code for  @that other guy
//def process = "echo hello world".execute()
def process = "../src/check_job_log.s ${it}.log".execute()
print "Output: " + process.text
print "Exit code: " + process.exitValue()

Output: Exit code: 01

【问题讨论】:

    标签: shell groovy return-value


    【解决方案1】:

    使用Process.exitValue() 代替(或补充).text

    def process = "echo hello world".execute()
    print "Output: " + process.text
    print "Exit code: " + process.exitValue()
    

    【讨论】:

    • $ksh ../src/check_job_log.s sb_sp_get_ucd_test.sql.log $echo $? 0
    • 你的代码输出是:Output: Exit code: 01。但是从上面你可以看到命令行的输出是:0。为什么这个01和0不一样?
    • 我的代码输出应该是Output: hello world, Exit code: 0。你有别的东西吗?
    • 我用我的代码替换了你的hello world,没有正确的输出,但是退出代码(01)与我从命令行运行相同的脚本0不同。我也测试了您的代码,退出代码是 01,而不是 0。
    • 祝福 groovy
    【解决方案2】:

    为什么这些命令有不同的输出?

    $../src/check_job_log.s dml_ucd_test.sql.log
    /iiss/prod/sql>
    $echo $?
    1
    /iiss/prod/sql>
    $../src/check_job_log.s dml_ucd_test.sql.log | echo $?
    0
    ops@uaiisst3:/iiss/prod/sql>
    $
    

    【讨论】:

      猜你喜欢
      • 2022-08-20
      • 2021-05-29
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      相关资源
      最近更新 更多