I have one bash source run.sh
as follows,
#!/bin/bash
if [ $# -ne 1 ]; then
exit
fi
...
when I execute it in two ways, there are different behaviors. The first way is,
source run.sh
It will close the terminal after execution. The second way is,
./run.sh
this will simply finish running the script, and stay on the terminal. I am asking if there is a command for exiting a bash scripts for both source run.sh
and ./run.sh
execution. I have tried return
too, which does not work well under ./run.sh
execution.
More generally, I am interested in why this is happening, and what's difference between using "source" and "." for script execution?
Best Answer
Before answering, I think some clarifications are needed. Let's analyze the following three lines:
The first two lines are exactly identical:
.
is in fact an alias forsource
. Whatsource
does is executing the shell script in the current context, hence a call toexit
will quit the shell.The third line (which is the one that confuses you) has however nothing to do with the other lines.
./run.sh
is just a path, and is the same as (for example)/home/user/run.sh
or/usr/bin/something
. Always remember that commands in the shell are separated by a space. So, in this case, the command is not.
, but is./run.sh
: this means that a sub-shell will be executed and that theexit
will have effect just to the sub-shell.