4

I have a script library that uses a lot of exit commands if some condition occurs. Each time an exit is hit, the shell is closed.

I saw many answers regarding this question that suggest changing the script, but my scripts are 3rd party and I assume the authors didn't mean that the shell should close so I assume there is some other way to run.

How do I run these script so that only the script stops but the shell remains open. Currently I use . script.sh.

2
  • the important question is: do you need the output of the child process, or do you just want the main-shell to stay alive Commented Sep 18, 2018 at 9:42
  • 3
    @grunt Why are you running it with . script.sh?! ./script.sh would do exactly what you want. Commented Sep 18, 2018 at 10:20

3 Answers 3

4

Instead of launching your script as . script.sh, you can launch it bash script.sh. When you launch it with bash then a child process for bash will be opened and your script will execute in the child shell and exit statements will make child shell closed and have no scope for parent shell or main shell.

Sign up to request clarification or add additional context in comments.

2 Comments

good answere, but OP did not say what he inteds to do (see my comment in his question)
@clockw0rk I see your comment and I am waiting for OP response so I can add my input. :)
3

If you are sourcing the script library and want to use all functions defined by the script library without causing the shell to exit use nested subshell.

Example:

# script.sh contents
hello_exit() { 
    echo "hello"; 
    sleep 1; 
    exit 10; 
}

# YOUR SHELL
source script.sh

# Use subshell
(hello_exit)

# If you want to capture the output and error code
output=$(hello_exit)
rc=$?

Comments

1

Add to script's start

trap $SHELL EXIT

2 Comments

OP says the scripts are third party, so anything requiring editing them won't be a solution for this question.
Well add it before source script.sh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.