To prevent source test.sh from exiting the current shell when test.sh contains exit, you need to ensure that the exit command in the script does not terminate the parent shell.
Why does this happen?
When you source (or .) a script, it runs in the current shell context. So, if the script contains exit, it will exit the current shell.
Solutions
1. Replace exit with return
If test.sh is meant to be sourced (not executed as a standalone script), use return instead of exit:
bash
return
return exits the current subshell or sourced script, not the parent shell.
2. Use a subshell
If you want to keep exit in the script, run it in a subshell:
bash
bash test.sh
This runs the script in a new shell, so exit only affects that subshell.
3. Guard the exit
If you must keep exit and want to source the script, add a guard:
bash
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
exit
fi
This checks if the script is being executed directly (not sourced). If sourced, exit is skipped.
Recommendation
For scripts meant to be sourced, use return. For standalone scripts, use exit.
Jul 13, 4:52pm
This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.