Environment: GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin20)
I'm attempting to trap the exit from another function but then continue executing the program. In an object oriented language you could catch an exception and then continue execution without re-throwin; that is essentially what I'm trying to do. I'm expecting the function foo() to exit, but in this case I want to catch it and continue execution of the program.
#!/bin/bash
function doNotExitProgram()
{
echo "Ignoring EXIT"
# Magic happens here
}
trap doNotExitProgram EXIT
function foo()
{
echo "Inside foo()"
exit 170
}
foo
echo "Continue execution here"
Expected:
Inside foo()
Ignoring EXIT
Continue execution here
Actual:
Inside foo()
Ignoring EXIT
Steps tried so far:
Tried using
shopt -s extdebugbut that doesn't seem to work with EXIT.Tried
trap - EXITinsidedoNotExitProgram()Tried
trap - EXITreturnreturn 0insidedoNotExitProgram()Tried
trap - EXITreturnreturn 1insidedoNotExitProgram()Tried
return 0insidedoNotExitProgram()Tried
return 1insidedoNotExitProgram()Tried
trap "" EXITinsidedoNotExitProgram()
This scenario is not described on Traps on tldp.org or on the trap man page.
EDIT: If possible do not change foo()
try exit 1; catch echo got error $?; done; echo continuing the main script. currently, we can emulate this with subshells, see also Is there a TRY CATCH command in Bash. but currently, there is no native try/catch in bash. there is try/catch in powershell