在shell脚本中`set -o errtrace`有什么作用? [英] What does `set -o errtrace` do in a shell script?

查看:318
本文介绍了在shell脚本中`set -o errtrace`有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此语句在shell脚本中有什么作用?

What is the effect of this statement in a shell script?

set -o errtrace

推荐答案

摘自手册:

errtrace 与-E相同.

errtrace Same as -E.

-E如果设置,则ERR函数上的任何陷阱都将被shell函数继承, 命令替换,以及在子命令中执行的命令 外壳环境. ERR陷阱通常不是固有的 在这种情况下会出事.

-E If set, any trap on ERR is inherited by shell functions, command substitutions, and commands executed in a sub‐ shell environment. The ERR trap is normally not inher‐ ited in such cases.

启用errtrace时,如果在函数或子shell中发生错误(返回非零代码的命令),也会触发ERR陷阱.另一种表达方式是,除非启用errtrace,否则函数或子Shell的上下文不会继承ERR陷阱.

When errtrace is enabled, the ERR trap is also triggered when the error (a command returning a nonzero code) occurs inside a function or a subshell. Another way to put it is that the context of a function or a subshell does not inherit the ERR trap unless errtrace is enabled.

#!/bin/bash

set -o errtrace

function x {
    echo "X begins."
    false
    echo "X ends."
}

function y {
    echo "Y begins."
    false
    echo "Y ends."
}

trap 'echo "ERR trap called in ${FUNCNAME-main context}."' ERR
x
y
false
true

输出:

X begins.
ERR trap called in x.
X ends.
Y begins.
ERR trap called in y.
Y ends.
ERR trap called in main context.

未启用errtrace时:

X begins.
X ends.
Y begins.
Y ends.
ERR trap called in main context.

这篇关于在shell脚本中`set -o errtrace`有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆