Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  19] [ 0]  / answers: 1 / hits: 11993  / 3 Years ago, sun, october 17, 2021, 6:04:00

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?


More From » bash

 Answers
1

Before answering, I think some clarifications are needed. Let's analyze the following three lines:



source run.sh
. run.sh
./run.sh


The first two lines are exactly identical: . is in fact an alias for source. What source does is executing the shell script in the current context, hence a call to exit 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 the exit will have effect just to the sub-shell.


[#40145] Tuesday, October 19, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ticeate

Total Points: 497
Total Questions: 128
Total Answers: 112

Location: Samoa
Member since Fri, Nov 27, 2020
4 Years ago
;