local variables in bash

Jon Jensen jon at endpoint.com
Thu Feb 12 19:10:30 MST 2009


On Thu, 12 Feb 2009, Shane Hathaway wrote:

>> This is a problem with bash - that is if one function calls another the 
>> value of the local variables are seen.
>
> It's a surprise, but it follows the bash documentation.
>
> $ help local
> local: local name[=value] ...
>    Create a local variable called NAME, and give it VALUE.  LOCAL
>    can only be used within a function; it makes the variable NAME
>    have a visible scope restricted to that function and its children.
>
> The "... and its children" specification is different from most 
> programming languages that I'm familiar with.  I guess bash searches the 
> call stack for variables, rather than use scoping rules like most 
> languages.  Another reason not to write anything complex in bash. :-)

This is just like Perl's "local", which provides temporary scoping to a 
global variable. It's not much used, with "my" being more what people are 
usually looking for. See man perlsub for details, section "Temporary 
Values via local()".

I wouldn't be surprised if bash borrowed the behavior & the name from 
Perl.

Jon

-- 
Jon Jensen
End Point Corporation
http://www.endpoint.com/



More information about the PLUG mailing list