1

I am writing a shell script. That shell script is executed in a bash shell inside a terminal. It contains a central error handler function. Please see the following basic demo snippet:

function error_exit
{
   echo "Error: ${1:-"Unknown Error"}" 1>&2
   exit 1 # This unfortunately also exits the terminal
}

# lots of lines possibly calling error_exit
cd somewhere || error_exit "cd failed"
rm * || error_exit "rm failed"
# even more lines possibly calling error_exit

The error handler function should end the script but should NOT end the terminal. How can I achieve this?

1 Answer 1

2

Use bash's trap builtin to spawn a bash instance upon the script's exit:

trap 'bash' EXIT

From help trap:

trap: trap [-lp] [[arg] signal_spec ...]
    Trap signals and other events.

    Defines and activates handlers to be run when the shell receives signals
    or other conditions.

    ARG is a command to be read and executed when the shell receives the
    signal(s) SIGNAL_SPEC.  If ARG is absent (and a single SIGNAL_SPEC
    is supplied) or `-', each specified signal is reset to its original
    value.  If ARG is the null string each SIGNAL_SPEC is ignored by the
    shell and by the commands it invokes.

    If a SIGNAL_SPEC is EXIT (0) ARG is executed on exit from the shell.

So by running trap 'bash' EXIT, bash will be read and executed when the shell receives the signal EXIT; spawning an interactive shell will consequentially have the effect of preventing the terminal from closing:

function error_exit
{
   echo "Error: ${1:-"Unknown Error"}" 1>&2
   exit 1 # This unfortunately also exits the terminal
}

trap 'bash' EXIT
# lots of lines possibly calling error_exit
cd somewhere || error_exit "cd failed"
rm * || error_exit "rm failed"
# even more lines possibly calling error_exit

You must log in to answer this question.

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