Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers 2

up vote 7 down vote accepted

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.

share|improve this answer
add comment

Three ways:

You can enclose the script in a function and only use return.

#!/usr/bin/env bash
main() {
    ...
    return 1
    ...
}
main "$@"

You can test if the script is being sourced by an interactive shell.

if [[ $- = *i* ]]; then
    return 1
else
    exit 1
fi

You can try to return, and if it fails, exit.

return 1 2>/dev/null || exit 1
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.