local marked function variables unavailable inside trap function - (d)ash shell

216 views Asked by At

I've read that the local keyword introduces dynamic scoping, meaning the variable defined thus in a function will be visible until the function dies. Hence visible and changeable in other functions that this function calls etc. However it seems that if there's a subshell inside a function (so the scope of the function will outlive the subshell), the local variable are, as expected, available inside the subshell normally, unless the trap function gets called. Inside the trap function, the variables defined as local in the outer (containing the subshell) function are unavailable. I tested in bash and don't see this problem, but I need to write ash/dash script and don't know if it's anything to do with some sort of POSIX rule.

Can someone please explain why in the following example (in ash) $a and $b error out in trap (due to set -u) while $c and $d work fine ?

#!/usr/bin/env ash

f() {

     local a='This gives an error in g() below: "a: parameter not set"';

     local b='This gives an error in g() below: "b: parameter not set"';

     c='Works fine';

     (

     set -e;

     set -u;

     # even though it's defined again in subshell, it's still unavailable in trap function

     b='This gives an error in g() below: "b: parameter not set"';

     d='Works fine';

     g() {

         printf 'Trap\n';

         printf 'd=%s\n' "${d}"; #fine

         printf 'c=%s\n' "${c}"; #fine

         printf 'b=%s\n' "${b}"; #error

         printf 'a=%s\n' "${a}"; #error

     }

     trap g INT QUIT TERM HUP EXIT;

     )

}

f;
0

There are 0 answers