如何在 TRAP ... RETURN 中获取 return 代码?

How to get return code in TRAP ... RETURN?

这是我的代码:

function my::return() {
    exit_code="" 
    echo "exit status of last command: ${exit_code}"
}

function testing(){
    trap 'my::return $?' RETURN
    return 2
}

如果我 运行 测试我希望 exit_code 为 2,因为 tyhis 是 return 中的代码,陷阱会捕获。

假设您只关心捕获函数的退出状态,而不是使用陷阱,您可以考虑使用包装函数:

$ trace_function() {
  local result
  $@
  result=$?
  echo " completed with status $result"
}

$ trace_function false
>false completed with status 1

$ trace_function true
>true completed with status 0

$ your_own_function() {
    if [ "$RANDOM" -gt "" ]; then
      echo ok
      return 0
    else
      echo ko
      return 1
    fi
}

$ trace_function your_own_function 16384
>ko
>your_own_function completed with status 1

$ trace_function your_own_function 16384
>ok
>your_own_function completed with status 0

这是我能想到的最好的办法

function my-func(){
  trap 'my::return $rc' RETURN
  local rc=2
  return $rc
}

这个:

#!/usr/bin/env bash

handler(){
        echo "From lineno:  exiting with code  (last command was: )"
        exit ""
}

foo(){
        echo "Hey I'm inside foo and will return 123"
        return 123
}

trap 'handler "$LINENO" "$?" "$BASH_COMMAND"' ERR

foo

echo "never going to happen"

将输出:

Hey I'm inside foo and will return 123
From lineno: 15 exiting with code 123 (last command was: return 123)

请注意,捕获 ERR 可能会捕获比您想要的更多的东西...

或者,您可以捕获 EXIT(和 set -e),但我不会那样做(set -e 是有争议的并且有警告)。