On 2/19/15 2:54 PM, Paul Donohue wrote: > The RETURN trap does not see the exit status of 'return', but rather the exit > status of the last command before 'return' was called. > > Example: > $ test_fun() > { > trap 'echo returned $?' RETURN > false # exit status is 1 > return 2 > } > $ test_fun > returned 1 > $ > > I intuitively expected the above to print 2 instead of 1. > > The bash man page states "Any command associated with the RETURN trap is > executed before execution resumes after the function or script." This is a > bit vague, but it seems to imply that the RETURN trap should run after the > `return` command is complete (since the `return` command is part of the > function and the RETURN trap runs "after the function"), which would imply > that $? should be set to the exit status of the return command in the RETURN > trap. So, the documentation seems to back up my intuition here... > > The problem I was actually trying to solve was to write a trap that ran only > if the function returned an error. An ERR trap would have been run if any > command within the function returned an error, which was not what I wanted. > So, I simply wrote a RETURN trap which checked $?, but $? did not give me the > return status of the function, so this didn't work.
The RETURN trap is run in the function's context, so this approach will probably not do what you want. The idea is that the trap allows the function writer to do cleanup while still seeing variables in the function's scope, for example. It's not intended to reflect the state after the function's execution context is unwound. As I recall -- and this was a long time ago -- it came in as part of the bash debugger changes and these were the semantics from the start. Chet -- ``The lyf so short, the craft so long to lerne.'' - Chaucer ``Ars longa, vita brevis'' - Hippocrates Chet Ramey, ITS, CWRU c...@case.edu http://cnswww.cns.cwru.edu/~chet/