以最小(优雅)的方式检查返回码

时间:2014-12-17 12:42:30

标签: bash shell

如何使这项工作?

#!/bin/bash
# this code is ugly and does not work
check_if_failed() {
    echo "arg1: $1"
    echo "arg2: $2"
    if [ $1 -ne 0 ] ; then
        exit $1
    fi
}

CHECK="check_if_failed $? $LINENO"

true ; $CHECK
false ; $CHECK

# (edit)
if true ; then
    false ; $CHECK
fi

目标是使用一个非常小的命令来检查返回码,以便我可以以简单的方式将它附加到每个命令行。

2 个答案:

答案 0 :(得分:2)

为什么要在每个要检查的命令后添加内容?让bash为你做吧!

#!/bin/bash

trap 'echo "Line $LINENO returned $?"' ERR

true
false || :  # this will not be checked
false       # this will be checked

答案 1 :(得分:1)

我认为您正在寻找的只是

some_command || exit

与在C中一样,||短路,因此如果左侧评估为" false"则仅评估其右侧。 (这里将其解释为非零返回码)。

相关问题