【问题标题】:Bash trap unset from function从函数中取消设置 Bash 陷阱
【发布时间】:2015-06-07 07:25:36
【问题描述】:

http://fvue.nl/wiki/Bash:_Error_handling#Set_ERR_trap_to_exit

为什么需要set -o errtrace 才能使函数调用中的陷阱设置/取消设置起作用?

#!/usr/bin/env bash

function trapit {
    echo 'trapped in a box'
}

function setTrap {
    trap 'trapit' ERR
}

function unsetTrap {
    trap - ERR
}

function foo_init {
    fooOldErrtrace=$(set +o | grep errtrace)
    set -o errtrace
    trap 'echo trapped' ERR   # Set ERR trap
}

function foo_deinit {
    trap - ERR                # Reset ERR trap
    eval $fooOldErrtrace      # Restore `errtrace' setting
    unset fooOldErrtrace      # Delete global variable
}

# foo_init
setTrap
echo 'set'
false

echo 'unset'
#foo_deinit
unsetTrap
false

【问题讨论】:

    标签: linux bash terminal


    【解决方案1】:

    根据 man bash(5) 的说法,如果没有打开 errtrace 标志,函数不会继承 ERR 陷阱。我不知道为什么默认情况下不能继承 ERR 陷阱,但是......现在是这样:)

    您可以使用我的示例代码测试此行为:

    #!/usr/bin/env bash
    trapit ()  {
     echo 'some error trapped'
    }
    
    doerr1 () {
     echo 'I am the first err generator and i return error status to the callee'
     return 1
    }
    
    doerr2 () {
     echo 'I am the second err generator and i produce an error inside my code'
     fgrep a /etc/motttd
     return 0
    }
    
    [[ $1 ]] && set -o errtrace
    
    trap trapit ERR
    
    doerr1
    
    doerr2
    
    echo 'We will produce an exception in the main program...'
    cat /etc/ftab | fgrep a
    
    echo 'OK, thats done, you see it :)'
    

    如果你向这个脚本传递任何参数,errtrace 标志将被打开,你会看到当 doerr2 试图做一些糟糕的事情时,异常被“捕获”了。

    【讨论】:

    • 困扰我的是从函数设置的陷阱是在全局范围内设置的,但不能以相同的方式取消设置。您可以全局设置某些内容,但不能以相同的方式取消设置。我想知道为什么。
    猜你喜欢
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    相关资源
    最近更新 更多