Pio*_*ost 4 linux error-handling bash shell bash-trap
似乎on_errorBash中的陷阱仅在其定义的函数范围内起作用.例如,运行此脚本
#!/bin/bash
on_error() {
echo 'on_error'
}
f() {
false
echo 'function f'
}
g() {
trap on_error ERR
echo 'function g'
false
f
}
g
Run Code Online (Sandbox Code Playgroud)
生产:
function g
on_error
function f
Run Code Online (Sandbox Code Playgroud)
有没有办法on_error全局陷阱,这样我就不必分别将它捕获到每个函数中?
默认情况下,ERRshell函数不会继承该陷阱.
引用自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
Run Code Online (Sandbox Code Playgroud)
话
set -o errtrace
Run Code Online (Sandbox Code Playgroud)
在脚本的开头应该使它按预期工作.