4

Within bash, how can a RETURN handler access the current return code?

For example

#!/usr/bin/env bash

function A() {
    function A_ret() {
        # How to access the return code here?
        echo "${FUNCNAME} ???"
    }
    trap A_ret RETURN
    echo -n "${FUNCNAME} returning code $1 ... "
    return $1
}
A 1

This prints

A returning code 1 ... A_ret ???

I would like it to print

A returning code 1 ... A_ret 1

How can A_ret access A return code?


Similar to this stackoverflow question Get the exitcode of the shell script in a “trap EXIT”.

Community
  • 1
  • 1
JamesThomasMoon
  • 4,639
  • 6
  • 33
  • 42

1 Answers1

2

It looks like the RETURN trap executes before the return statement actually sets the new value of $?. Consider this example that sets $? just before the return statement.

a () {
    a_ret () {
        echo "${FUNCNAME} $?"
    }
    trap a_ret RETURN
    printf "${FUNCNAME} returning code $1 ... "
    (exit 54)
    return $1
}

a 1

In bash 3.2 and 4.3, I get as output

a returning code 1 ... a_ret 54

I'd say this is a bug to report. As a workaround, you can always use the subshell exit with the value you intend to return:

a () {
    ...
    (exit $1)
    return $1
}
chepner
  • 446,329
  • 63
  • 468
  • 610