At the point where you execute exit 2
, you can't tell how many "levels" of shell need to exit. The best you can do is use the exit status of the loop to see if that level should exit as well. For example,
echo foobar | while read blabla; do
x=$(foo)
if [ "$x" = bar ]; then
exit 0 # We're done with the loop, success
elif [ "$x" = gulp ]; then
exit 1 # We're done with the loop, failure
else
exit 2 # We're done with the script, abort!
fi
done
case $? in
2) printf 'Fatal error in loop, exiting
' >&2; exit 1 ;;
*) printf 'Loop result %d, continuing
' ;;
esac
printf 'Continuing script...'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…