子脚本之一失败时不退出bash脚本 [英] not exit a bash script when one of the sub-script fails

查看:63
本文介绍了子脚本之一失败时不退出bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to shell script. I have a script that runs several test scripts using different input files. Currently it exits if any one of the input test fails. I want the test to complete running the loop and exits with all errors accumulated at last.

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

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

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

:
:
:
exit $?

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

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

推荐答案

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

set -e is what causes your script to exit immediately after a failed command. Get rid of it.

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

If you want the exit status to be 1 if any test fails, try out the following:

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.

The value of exit_status will only be changed from 0 to 1 if an invocation of test_script.sh has a non-zero exit status.

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

Update: you can collect the failed scripts in an array (which you should also be using to store the list of files):

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

这篇关于子脚本之一失败时不退出bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆