The following trick allows the script to gracefully exit without terminating the shell, whether sourced or direct execution:
instead of exit, use this:
[[ $PS1 ]] && return $? || exit $?
Alternately, define this function and call it instead of exit
:
__EXIT__()
{
[[ $PS1 ]] && return $1 || exit $1
}
....
__EXIT__ $?