On Thu, Feb 06, 2025 at 18:41:14 +0100, Phi wrote:
> I find the docco for return [n] not easy to interpret. Here is what can be 
> read.
> 
>        return [n]
>               Stop executing a shell function or  sourced  file  and
>               return  the  value specified by n to its caller. 
>               ...
>               Any  command  associated  with the RETURN trap is exe‐
>               cuted before execution resumes after the  function  or
>               script.

In the FUNCTIONS section, there is some additional wording:

       All other aspects of the shell execution environment are identical  be‐
       tween  a  function  and its caller with these exceptions: the DEBUG and
       RETURN traps (see the description  of  the  trap  builtin  under  SHELL
       BUILTIN  COMMANDS below) are not inherited unless the function has been
       given the trace attribute (see the description of the  declare  builtin
       below)  or  the -o functrace shell option has been enabled with the set
       builtin (in which case all  functions  inherit  the  DEBUG  and  RETURN
       traps),  and the ERR trap is not inherited unless the -o errtrace shell
       option has been enabled.

> $ function f { :; }
> $ trap "echo catch return" RETURN
> $ . /dev/null # Hurray!
> catch return

The RETURN trap fired upon "returning" from a . command, because the
trap was set within the main script, not within the function f.

> $ f # huh ?

The RETURN trap was not inherited by the function f, because the function
was not "given the trace attribute", and the functrace shell option is not
enabled.

> $ shopt -s extdebug
> $ f # ha!
> catch return

I suppose extdebug must imply functrace, then.

> As any gurus out there knows the function return trap is only available with 
> shopt -s extdebug, that is not explicitly stated in the documentation, and 
> its a pain.

I guess I'm not a guru.

Anyway, based on the part of the documentation that I cited, the RETURN
trap seems to work fine if it's defined within the function.

hobbit:~$ f1() { echo f1; }
hobbit:~$ f2() { trap 'echo TRAP' RETURN; echo f2; }
hobbit:~$ f1
f1
hobbit:~$ f2
f2
TRAP
hobbit:~$ f1
f1
hobbit:~$ f2
f2
TRAP

If extdebug really does imply functrace, then that's missing from the
documentation.  The rest appears to be working as intended.

Reply via email to