如何在 bitbake 配方上捕获命令的退出代码?

How can I catch exit codes of a command on a bitbake recipe?

我有一个 bitbake 食谱,在从远程服务器下载一些包之前,我需要在其中检查远程服务器的可用性。为此,我使用 ping 如下:

ping ${HOST} -c1 -w4 1>/dev/null 2>/dev/null
if [ $? -ne 0 ]; then
    echo "ERROR: Unable to reach ${HOST}. Exiting now with code $?..."
    exit $? 
fi

上面的代码在终端中工作得很好,我得到了相应的退出代码:0 表示 OK,非零表示 NOK。

然而,bitbake 配方上的代码完全相同,退出代码 $? 始终为空。相反,bitbake 本身会捕获错误代码,然后继续执行。稍后,当尝试解压缩未下载的文件时,它会失败。那时,我收到了关于 ping 更早抛出的非零退出代码的警告。目前是这样的:

if [ "$(ping ${HOST} -c1 -w4 1>/dev/null 2>/dev/null)" = 0 ]; then
    echo "ERROR: Unable to reach ${HOST}. Exiting now..."
    exit 1 
fi

# Some other stuff here...

ar -x ${BUILDDIR}/tmp/deploy/ipk/all/rheas_*.ipk

我得到:

ERROR: rheas-0.0-r0 do_compile: Function failed: do_compile (log file is located at /data/oe-core/build/tmp/work/armv5te-poky-linux-gnueabi/rheas/0.0-r0/temp/log.do_compile.2239)
ERROR: Logfile of failure stored in: /data/oe-core/build/tmp/work/armv5te-poky-linux-gnueabi/rheas/0.0-r0/temp/log.do_compile.2239
Log data follows:
| DEBUG: Executing shell function do_compile
| ar: /data/oe-core/build/tmp/deploy/ipk/all/rheas_*.ipk: No such file or directory
| WARNING: exit code 9 from a shell command.
| ERROR: Function failed: do_compile (log file is located at /data/retail-renos-oe-core/build/tmp/work/armv5te-poky-linux-gnueabi/rheas/0.0-r0/temp/log.do_compile.2239)
ERROR: Task (/data/oe-core/meta-renos/recipes-core/rheas/rheas_0.0.bb:do_compile) failed with exit code '1'

总而言之,我自己无法使用退出代码,因为 bitbake 似乎以某种方式劫持了它。

问题是我无法抛出用户友好的错误,而其他人永远不知道问题出在哪里。

所以我的问题是:如何在 bitbake 配方中使用退出代码?

在这个项目中,我特别使用了 bitbake 版本 1.32.0。

手册中似乎没有这个答案。

bitbake 默认使用更安全的 set -e:脚本执行在第一个错误时停止。

您可以禁用此功能(使用 set +e),但我建议改为专门处理单个 known-to-fail 命令。有几种方法可以做到这一点,这是一个示例(这也修复了代码中使用 echo 的退出值作为退出值的错误):

err=0
ping ${HOST} -c1 -w4 1>/dev/null 2>/dev/null || err=$?
if [ $err -ne 0 ]; then
    echo "ERROR: Unable to reach ${HOST}. Exiting now with code $err..."
    exit $err 
fi