How to make a bash function return 1 on any error

天涯浪子 提交于 2019-12-04 10:23:26

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=0
SUCCESS=0
for (( i = 0; i < 10; i++ )); do
  randomly_fail
  if (( $? != 0 )); then
      (( FAILED += 1 ))
  else
    (( SUCCESS += 1 ))
  fi
done

echo "$SUCCESS success, $FAILED failed"

This will output something like

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