linuxbash

Is there a way to exit a Bash script, but not quitting the terminal?


When I use exit command in a shell script, the script will terminate the terminal (the prompt). Is there a way to terminate a script and then staying in the terminal?

My script run.sh is expected to execute by directly being sourced, or sourced from another script.

To be more specific, there are two scripts, run2.sh as

...
. run.sh
echo "place A"
...

and run.sh as

...
exit
...

when I run it by . run2.sh, and if it hit exit codeline in run.sh, I want it to stop to the terminal and stay there. But using exit, the whole terminal gets closed.

PS: I have tried to use return, but echo codeline will still gets executed...


Solution

  • The "problem" really is that you're sourcing and not executing the script. When you source a file, its contents will be executed in the current shell, instead of spawning a subshell. So everything, including exit, will affect the current shell.

    Instead of using exit, you will want to use return.