How to make a bash function return 1 on any error How to make a bash function return 1 on any error bash bash

How to make a bash function return 1 on any error


If your function doesn't need to set any global variables, you can have the function create a subshell in which set -e is used. The subshell will exit, not the shell in which has_error is called.

has_error () (    # "(", not "{"  set -e  true  echo "Ok..."  false  echo "Shouldn't be here!")


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