Trapping exit and continuing

Hello

I need to source a script. But that script terminates with a trailing exit. Which exits my script. I'm using bash, and this doesn't work:

trap 'echo disabled' EXIT
source other_file
trap '' EXIT

Instead, it calls my trap, but then exits anyway. I could get disgusting and tricky (execute remainder of code in the trap hook), but I don't want to. Any elegant solutions?

When exit is called, the shell will exit, regardless of any traps that have been set.

The most palatable workaround that comes to mind:

exit() { :;}
source other_file
unset -f exit

Aliasing may also be an option, but the following will most likely fail unless the shell is in interactive mode or a sh option specifiying expansion of aliases in non-interactive mode is enabled.

alias exit=:
source other_file
unalias exit

Either solution will evaluate exit's args, so if they have side effects those effects will occur (though this seems to me unlikely with an exit command).

Regards,
Alister

---------- Post updated at 03:53 PM ---------- Previous update was at 03:30 PM ----------

If the only occurrence of "exit" in the script is as a command name, then you can also do the following:

eval "$(sed 's/exit/:/g' other_file)"

If exit only occurs on a line by itself:

eval "$(sed '/exit/d' other_file)"
1 Like

Great thanks. I know you meant to write:

function exit() {:;}
source file
unset -f exit

Appreciate the help.

You're quite welcome, for the help.

Regarding the function definition, nope, I meant exactly what I typed. posix sh function definitions do not use the "function" keyword. In shells that do support functions defined using the "function" keyword (e.g. ksh), they behave a bit differently (mostly with respect to positional parameters) than those defined without it.

The space after the opening brace is needed (confirmed in ksh and bash).

Your function definition seems to be some odd hybrid of two different syntaxes. Syntax one (posix-compliant) does not use the "function" keyword and requires parenthesis after the function's name. Syntax two (ksh-style, I presume) uses the "function" keyword and does not require any parenthesis. You are using both the "function" keyword and parenthesis.

What kind of mutant shell are you using? :wink:

On an unrelated note, my ksh93 considers "exit" an illegal function name, but bash has no problem with it.

Regards,
Alister

1 Like

<deleted> I misread part of your response.