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

拟墨画扇 提交于 2020-06-16 17:29:29

问题


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.

main.sh

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

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

test_script.sh : runs few stuff and exits like this.

:
:
:
exit $?

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


回答1:


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

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"

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


来源:https://stackoverflow.com/questions/62183201/not-exit-a-bash-script-when-one-of-the-sub-script-fails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!