在错误处理函数中退出shell脚本而不退出终端

在错误处理函数中退出shell脚本而不退出终端

bash我正在编写一个 shell 脚本。该 shell 脚本在终端内的 shell中执行。它包含一个中央错误处理函数。请参阅以下基本演示片段:

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

错误处理函数应该结束脚本,但不应该结束终端。我该如何实现这一点?

答案1

使用bash内置函数在脚本退出时trap生成一个实例:bash

trap 'bash' EXIT

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.

因此通过运行trap 'bash' EXITbash将在 shell 接收到 EXIT 信号时读取并执行;生成一个交互式 shell 最终将起到防止终端关闭的效果:

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

相关内容