How to make a bash function return 1 on any error
The answer by @chepner helped me, but it is incomplete.
If you want to check function return code, don't put function call inside if
statement, use $?
variable.
randomly_fail() ( set -e echo "Ok..." (( $RANDOM % 2 == 0 )) echo "I'm lucky")FAILED=0SUCCESS=0for (( i = 0; i < 10; i++ )); do randomly_fail if (( $? != 0 )); then (( FAILED += 1 )) else (( SUCCESS += 1 )) fidoneecho "$SUCCESS success, $FAILED failed"
This will output something like
Ok...I'm luckyOk...I'm luckyOk...I'm luckyOk...Ok...I'm luckyOk...Ok...I'm luckyOk...Ok...Ok...I'm lucky6 success, 4 failed