当其中一个子脚本失败时不退出 bash 脚本

not exit a bash script when one of the sub-script fails

我是 shell 脚本的新手。我有一个脚本,它使用不同的输入文件运行多个测试脚本。目前,如果任何一个输入测试失败,它就会退出。我希望测试完成 运行 循环并退出并最终累积所有错误。

main.sh

set -e ;
set -x ;
for f in $files;do
    ./scripts/test_script.sh $f
done

======================

test_script.sh : 运行一些东西然后像这样退出。

:
:
:
exit $?

================

set -e 是导致脚本在命令失败后立即退出的原因。摆脱它。

如果您希望在任何测试失败时退出状态为 1,请尝试以下操作:

exit_status=0

for f in $files; do
  if ! ./scripts/test_script.sh "$f"; then
    exit_status=1
  fi
done

exit "$exit_status"

只有当 test_script.sh 的调用具有非零退出状态时,exit_status 的值才会从 0 更改为 1。


更新:您可以将失败的脚本收集到一个数组中(您也应该使用它来存储文件列表):

files=(foo.txt bar.txt)
failed=()

for f in "${files[@]}"; do
  ./scripts/test_script.sh "$f" || failed+=("$f")
done

if (( ${#failed[@]} != 0 )); then
  echo "Failed:"
  printf '  %s\n' "${failed[@]}"
  exit 1
else
  exit 0
fi