function set_trap_for_exception() {
function _on_error() {
echo "error start"
exit 1
}
trap '_on_error "$BASH_COMMAND" $LINENO' ERR
}
function is_hygon_cpu() {
vendor_id=$(lscpu | grep "value is not exist")
}
function main()
{
set_trap_for_exception
is_hygon_cpu
}
main
cmd: vendor_id=$(lscpu | grep "value is not exist") will error but -E is not set, output is: error start
if i put echo in function is_hygon_cpu, subshell is not trap:
function set_trap_for_exception() {
function _on_error() {
echo "error start"
exit 1
}
trap '_on_error "$BASH_COMMAND" $LINENO' ERR
}
function is_hygon_cpu() {
echo "start"
vendor_id=$(lscpu | grep "value is not exist")
echo "end"
}
function main()
{
set_trap_for_exception
is_hygon_cpu
}
main
output is: start end
By default, the subshell will not inherit the main shell's traps, but this phenomenon really makes me confused. Why does this happen? Do commands in and out of functions have any effect on traps? Why can't I capture them if I add an echo?
If a numeric argument is given to
return
, that is the function’s return status; otherwise the function’s return status is the exit status of the last command executed before thereturn
.
so
function is_hygon_cpu() {
vendor_id=$(lscpu | grep "value is not exist")
}
# return 1
function is_hygon_cpu() {
echo "start"
vendor_id=$(lscpu | grep "value is not exist")
echo "end"
}
# return 0