Please see What does source do?
source is a bash shell built-in command that executes the content of the file passed as argument, in the current shell. It has a synonym in . (period).
exit in a sourced script makes the current shell exit, as if you typed exit. A scripts that is meant to be sourced should never exit its main shell (i.e. not a subshell) because its main shell is the shell you source the script from. Unless you know what you're doing and exit in a sourced script is really what you want.
You can return from a sourced script. If you need to source the script then return 1 may be the right thing instead of exit 1.
A script that is not meant to be sourced should not be sourced. If it invokes exit in its main shell then it's most likely meant to be executed. Another useful link: What is the difference between sourcing (. or source) and executing a file in bash?
So how to execute?
A command bash scriptname will run a separate bash process that will parse scriptname and execute its lines. If there is exit then it will exit the separate bash, not your current shell.
To be able to execute a script directly (like ./scriptname instead of bash scriptname) you need a proper shebang as the first line of the script, e.g.:
#!/bin/bash
and the file needs to be executable (chmod +x scriptname) and the filesystem holding the file must not be mounted with noexec option.
exit 1in a shell script" in a script you source? (withsourceor.). – Kamil Maciorowski Aug 29 '19 at 22:40.orsource, it runs in the current shell. In your case, that means it's running in your interactive shell. When it exits, it exits your interactive shell. You need to either run it normally (as a subprocess) (note that running it with./scriptnameinstead of. scriptnamewill do this, provided it's executable and has a proper shebang), or have it usereturninstead ofexit. – Gordon Davisson Aug 30 '19 at 01:15