如何在TRAP ... RETURN中获得返回码?

时间:2019-05-09 08:52:15

标签: bash shell trap

这是我的代码:

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

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

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

3 个答案:

答案 0 :(得分:0)

这是我能想到的最好的

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

答案 1 :(得分:0)

此:

#!/usr/bin/env bash

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

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有争议并且有警告)。

答案 2 :(得分:-1)

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

$ trace_function() {
  local result
  $@
  result=$?
  echo "$1 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 "$1" ]; 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