How to get the exit status a loop in bash

后端 未结 8 783
醉梦人生
醉梦人生 2020-12-16 15:38

I know how to check the status of the previously executed command using $?, and we can make that status using exit command. But for the loops in bash are always returning a

8条回答
  •  春和景丽
    2020-12-16 16:06

    Something like this?

    while true; do
        case $RANDOM in *0) exit 27 ;; esac
    done
    

    Or like this?

    rc=0
    for file in *; do
        grep fnord "$file" || rc=$?
    done
    exit $rc
    

    The real question is to decide whether the exit code of the loop should be success or failure if one iteration fails. There are scenarios where one make more sense than the other, and other where it's not at all clear cut.

提交回复
热议问题