bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: bash-5.0: problem with variable scoping in posix-mode


From: Chet Ramey
Subject: Re: bash-5.0: problem with variable scoping in posix-mode
Date: Sun, 27 Jan 2019 17:59:25 -0500
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:60.0) Gecko/20100101 Thunderbird/60.3.3

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    chet@case.edu    http://tiswww.cwru.edu/~chet/



reply via email to

[Prev in Thread] Current Thread [Next in Thread]