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”.

4
  • Evaluate $? after you call your function within your script. Commented Aug 19, 2015 at 4:46
  • @DavidC.Rankin Per the title, the RETURN trap function, A_ret, needs to access the A return code. Commented Aug 19, 2015 at 8: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. Commented Aug 19, 2015 at 8: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. Commented Mar 11, 2023 at 0:09

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.