Exit Codes in Functions

Don’t use exit in bash functions, they should instead use return so that the calling script has the option of what to do on failure.

If set -o errexit is set then the script will still exit with failure, but if the calling script doesn’t want that to happen then they can add myFunc || true to stop it happening.

1
2
3
4
5
6
7
8
function bad {
  echo "# bye"
  return 1
}
function good {
  echo "# hi"
  return 0
}

Output:

1
2
3
4
5
6
7
bad; echo "# $?"
# bye
# 1

good; echo "# $?"
# hi
# 0