Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit running script without exiting shell

Tags:

bash

ubuntu

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.

like image 509
grunt Avatar asked Oct 17 '25 10:10

grunt


2 Answers

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.

like image 104
rɑːdʒɑ Avatar answered Oct 20 '25 00:10

rɑːdʒɑ


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=$?
like image 23
apatniv Avatar answered Oct 19 '25 23:10

apatniv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!