【问题标题】:How to get both exit code and standard output?如何同时获得退出代码和标准输出?
【发布时间】:2022-01-01 13:04:50
【问题描述】:

在 shell 中,例如 Bash 和 Zsh,我们可以使用 info=$(<command>) 获取命令的标准输出。例如:

info=$(./run-a-program arg1 arg2)

我们还可以从$? 获取退出代码。它对于像timeout 这样的命令很有用。例如:

# run the program in 10 seconds
timeout 10s ./run-a-program arg1 arg2
if (( $? == 124 )) {
  echo "Timeout!"
}

那么有没有办法同时获得退出代码和标准输出

【问题讨论】:

    标签: shell stdout exit-code


    【解决方案1】:

    你仍然可以使用$?:

    info=$(./run-a-program arg1 arg2)
    echo "run-a-program returned $?" 
    

    但请注意,您实际上很少需要直接引用$?。也许您想编写如下代码:

    info=$(./run-a-program)
    if [ $? = 0 ]; then ...; fi
    

    但这可以更好地写成:

    if info=$(./run-a-program); then ...; fi
    

    有时会使用除零/非零以外的特殊返回码,您可能需要使用case $? in,但这是您唯一需要明确引用$? 的时间。改掉看$?的习惯;如果你不这样做,代码更容易维护。

    【讨论】:

      猜你喜欢
      • 2010-09-11
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多