linux - 如何在全局范围内捕获 bash 中的 on_error?

标签 linux bash shell error-handling bash-trap

Bash 中的 on_error 陷阱似乎只在定义它的函数范围内起作用。例如运行这个脚本

#!/bin/bash

on_error() {
    echo 'on_error'
}

f() {
    false
    echo 'function f'
}

g() {
    trap on_error ERR
    echo 'function g'
    false
    f
}

g

产生:

function g
on_error
function f

有没有办法在全局范围内捕获 on_error,这样我就不必在每个函数中单独捕获它了?

最佳答案

默认情况下,ERR 陷阱不会被 shell 函数继承。

引用自 help set:

  -E  If set, the ERR trap is inherited by shell functions.

  -o option-name
      Set the variable corresponding to option-name:
          errtrace     same as -E

set -o errtrace

在脚本的开头应使其按预期工作。

关于linux - 如何在全局范围内捕获 bash 中的 on_error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21776575/

相关文章:

linux - 从 ls 输出中提取文件名和修改时间

bash - 在 shell 脚本中匹配所有带有井号(#)的单词

linux - 更改文件名并复制到不同的目录

linux - Jenkins Linux 从站输出

linux - Shell 脚本不从 cron 作业执行

bash - 为什么 grep\n 匹配每一行

bash - 使用 bash 打开新的控制台/lxterminal 窗口 - Raspbian Jessie Lite

linux - 不同命名空间中的套接字对应的文件描述符是否分配了相同的数值?

linux - 您可以在远程运行的 shell 脚本中提示用户输入吗?

bash - 使用变量时没有这样的文件或目录错误(否则工作)