Yes, setting the errexit
shell option with set -e
would make the current shell exit as soon as a command terminates with a non-zero exit status (unless the command is part of an AND/OR-list etc.)
This means you can't "externally" cause a sourced script to stop executing at the first error using set -e
.
However, another thing that happens in the bash
shell when set -e
would have triggered is that any ERR
trap would execute. This allows us to set a trap that simply does a return
.
$ cat script
echo hello
false
echo bye
$ . ./script
hello
bye
We would like the above script to stop executing when executing false
. We do this by setting a trap for ERR
. The trap first unsets itself before using return
. If the trap did not unset itself, we would get a complaint from the shell about trying to run return
without being in a function or sourced script. This is due to the trap activating a second time due to the non-zero return status of the sourced script.
$ trap 'trap - ERR;return' ERR
$ . ./script
hello
$ echo "$?"
1
Note that we have to set the trap each time we source the script.