bug-bash
[Top][All Lists]
Advanced

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

Re: Local variables overriding global constants


From: Chris F.A. Johnson
Subject: Re: Local variables overriding global constants
Date: Wed, 3 Apr 2013 04:33:48 -0400 (EDT)
User-agent: Alpine 2.00 (LMD 1167 2008-08-23)

On Wed, 3 Apr 2013, Pierre Gaston wrote:

On Wed, Apr 3, 2013 at 11:03 AM, Chris Down <chris@chrisdown.name> wrote:

On 2013-04-03 11:00, Nikolai Kondrashov wrote:
It doesn't work because you are trying to redefine an existing
readonly variable.

Yes, but I'm explicitly redefining it locally, only for this function.
And this works for variables previously defined in the calling
function.

You're not redefining it locally, you are unsuccessfully trying to
override a
global.


Still Nikolai has a point.
It's not clear why readonly variable can be overridden when the variable is
declared readonly in the scope of an englobing function but not if it is
declared readonly in the global scope.

   If it's declared readonly in a function, the variable doesn't exist
   outside of that function, so it's not readonly there.


$ bash -c 'a() {  v=2;echo "$v"; }; b () { declare -r v=1; a; echo "$v"; };
b'
bash: v: readonly variable

The variable is locale to b, but the readonly flag is preserved in a

$ bash -c 'a() { declare -r v=2;echo "$v"; }; b () { declare -r v=1; a;
echo "$v"; }; b'
2
1

The variable is locale to b, but you can redeclare it  locale to a even if
it has the readonly flag

$ bash -c 'declare -r v=2; b () { declare -r v=1; echo "$v"; }; b'
bash: line 0: declare: v: readonly variable
2

it looks like the same as the first case except that the variable is
declared readonly in the global scope.

(Also readonly defers from declare -r:
bash -c 'a() { declare -r v=2;echo "$v"; }; b () { readonly v=1; a; echo
"$v"; }; b; v=2'
$ bash -c 'a() { declare -r v=2;echo "$v"; }; b () { readonly v=1; a; echo
"$v"; }; b; v=2'
bash: line 0: declare: v: readonly variable
1
1
bash: v: readonly variable.

I seem to recall this has been discussed on this list at some point)


--
   Chris F.A. Johnson, <http://cfajohnson.com/>
   Author:
   Pro Bash Programming: Scripting the GNU/Linux Shell (2009, Apress)
   Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)



reply via email to

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