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.
1function bad {
2 echo "# bye"
3 return 1
4}
5function good {
6 echo "# hi"
7 return 0
8}
Output:
1bad; echo "# $?"
2# bye
3# 1
4
5good; echo "# $?"
6# hi
7# 0