Sample Header Ad - 728x90

How do you continue execution after using trap EXIT in bash?

1 vote
3 answers
4189 views
**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:** 1. Tried using shopt -s extdebug but that doesn't seem to work with EXIT. 2. Tried trap - EXIT inside doNotExitProgram() 3. Tried trap - EXIT return return 0 inside doNotExitProgram() 4. Tried trap - EXIT return return 1 inside doNotExitProgram() 5. Tried return 0 inside doNotExitProgram() 6. Tried return 1 inside doNotExitProgram() 7. Tried trap "" EXIT inside doNotExitProgram() This scenario is not described on [Traps on tldp.org](https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_12_02.html) or on the [trap man page](https://man7.org/linux/man-pages/man1/trap.1p.html) . **EDIT:** If possible do not change foo()
Asked by Yzmir Ramirez (165 rep)
Feb 16, 2022, 02:48 AM
Last activity: Jan 15, 2024, 11:09 AM