6

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
  • 6,169
  • 7
  • 37
  • 63
  • Evaluate `$?` after you call your function within your script. – David C. Rankin Aug 19 '15 at 04:46
  • @DavidC.Rankin Per the title, the `RETURN` trap function, `A_ret`, needs to access the `A` return code. – JamesThomasMoon Aug 19 '15 at 08:08
  • Yes, I stumbled into that. Triplee straightened me out. As below, the return from `trap` will always be `0` unless there is a signal specification error. Good question. – David C. Rankin Aug 19 '15 at 08:11
  • 1
    If you are not using set -e, then the RETURN trap is called twice for a return statement, the first time, without $? set yet, and the second time with $? set according to the return statement. – Johan Boulé Mar 11 '23 at 00:09

1 Answers1

5

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
  • 497,756
  • 71
  • 530
  • 681