1

When using bash in a terminal often scripts have to be run sourced. In such cases terminating the script must be done by "return", but not by "exit" in order to not kill the basic shell.

Can I as normal user somehow accomplish that option -e to apply "return" instead of "exit".

Regards

Anton Wessel

1 Answer 1

2

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.

2
  • Good answer. It led me to experiment, and I was successful placing the trap at the top of script to avoid having to set the trap externally each time.
    – Jim L.
    Nov 17, 2022 at 21:13
  • @JimL. Yeah, that would work too, for user with write access to the scripts in question.
    – Kusalananda
    Nov 17, 2022 at 21:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .