On 1/27/19 7:58 AM, Alexander Tsoy wrote:

> Bash Version: 5.0
> Patch Level: 2
> Release Status: release
> 
> 
> Description:
> 
> There is a problem with variable scoping when variable is created from
> assignment statement preceding function call in posix-mode. See an
> example below.
> 
> 
> Repeat-By:
> 
> $ cat test.sh 
> #!/bin/sh
> 
> myecho() {
>     echo $var
> }
> 
> foo() {
>     local var="foo: FAIL"
>     var="foo: bar" myecho
> }
> 
> foo
> 
> $ bash test.sh 
> foo: bar
> $ bash --posix test.sh 
> foo: FAIL

This is a consequence of a combination of two POSIX features. First, POSIX
requires assignment statements preceding special builtins to create global
variables (POSIX has no local variables) that persist in the shell context
after the special builtin completes. Second, POSIX requires* that
assignment statements preceding function calls have the same variable-
assignment behavior as special builtins.

So the variable assignment preceding the function call creates a global
variable, and the local variable is found before that global when `myecho'
is executed according to the standard bash dynamic scoping rules. If you
add an `echo $var' after the call to foo, you'll see this behavior.

(*) The most recent version of the standard has removed this requirement
for shell functions, and I will change that behavior for the next release
of bash. Until then, the old behavior persists.

Chet

-- 
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    c...@case.edu    http://tiswww.cwru.edu/~chet/

Reply via email to