结合地图文件、命令重定向和退出状态检索



我正在读取一个构建命令,如下所示:

mapfile -t make_out < <(2>&1 ./make.sh my_program)

如果构建失败,我只想打印保存在make_out中的输出。我如何既保持退出状态,又保存输出以备日后使用(考虑间距、换行和一般的安全解析(?

我愿意改变我阅读结果的方式,但我不希望解决方案将内容保存在额外的文件中或依赖于分析文本。如果不能做到这一点,它是有效的。

您可以启用lastpipe选项并将命令转换为管道;使得mapfile在当前执行环境中运行,并且可以从PIPESTATUS数组中检索到./make.sh的退出状态。

# call set +m first if job control is enabled
shopt -s lastpipe
./make.sh my_program 2>&1 | mapfile -t make_out
if [[ PIPESTATUS[0] -ne 0 ]]; then
printf '%sn' "${make_out[@]}"
fi
# revert changes to shell options if necessary

我最近想出了一些类似的东西。简而言之,提供退出代码作为最后一个数组元素并将其分割:

mapfile -t make_out < <(2>&1 ./make.sh my_program; echo ${?})
declare -ir exit_code=${make_out[-1]}
unset make_out[-1]
if ((exit_code != 0))
then
printf '%sn' "${make_out[@]}"
fi

最新更新