It's pretty much the same answer as for your otherwise-identical question on SuperUser.
When you run a shell script with
source) you are running it in the context of your interactive shell. Thus, when the shell hits an
exit command it exits your interactive shell.
The correct way to run a shell script is not to use
source) but to make it executable and just run it as if it were any other application. (The first line, starting with
#!, defines the interpreter for the script. In my example it's
/bin/bash but it could be anything that can read a script.)
Here is a worked example for a script that's called
# Create a trivial shell script called "tryit"
cat >tryit <<'X'
echo "This is my shell script"
# Make it executable
chmod +x tryit
# Now run it (the "./" prefix means "in the current directory")
If you put the
tryit script into a directory that is in your
$PATH you don't need (and must not use) the
./ prefix. Here is an example
# Create applications (bin) directory and add to PATH for this session
mkdir -p "$HOME/bin"
# Move the "tryit" application to the bin directory
mv tryit "$HOME/bin"
# Now we can run it just like any other application
I should probably point out that when running a script this way it is not possible to set environment variables in the current interactive shell. To do that you really do need to continue using
source, in which case you must remember that because the script runs in your interactive context you must not include an
exit statement anywhere.