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:11:38 -0400 (EDT)
User-agent: Alpine 2.00 (LMD 1167 2008-08-23)

On Wed, 3 Apr 2013, Nikolai Kondrashov wrote:

On 04/03/2013 10:53 AM, Chris Down wrote:
On 2013-04-03 10:50, Nikolai Kondrashov wrote:
On 04/03/2013 10:43 AM, Chris F.A. Johnson wrote:
On Wed, 3 Apr 2013, Nikolai Kondrashov wrote:
I.e. this:

bash -c 'declare -r v; a() { declare -r v; }; a'

Results in:

bash: line 0: declare: v: readonly variable

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.

How is this different?

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

   In a() you created a new, local variable, which you could do in
   this instance because it is not readonly.

While this works:

bash -c 'a() { declare -r v; }; b() { declare -r v; a; }; b'

It works because both instances are local to a function and don't
exist outside their own functions.

Not true.

This:

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

Produces this:

     123

That is *inside* the function, not *outside* the function.

I'd say that "v" is declared outside function "a", where it is accessed, or do
you mean that there is no concept of separate functions in Bash and all
"functions" are just one function?

   a() is a child of b(), so it can see its variables.

--
   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]