Shell Script Question
Alma J Wetzker
almaw
Wed Jun 1 17:31:48 PDT 2005
David Bandel wrote:
> On 6/1/05, Brad De Vries <devriesbj at gmail.com> wrote:
>
>>Hey all, I have a shell scripting question I'm hoping someone can
>>answer for me. Why doesn't a variable that is being set within a loop
>>retain its value when the loop is done?
>
>
> try Googling on something like "variable scope". When you declare a
> variable in any language I'm familiar with (for example, Perl), a
> variable declared within a program subsection is local to that
> subsection and is destroyed when that subsection exits. If you need a
> variable to have global scope (please, don't start making all your
> variables global), you need to declare it in a global context. Perl
> also has the notion of importing and exporting when dealing with
> modules.
>
> This can get sticky if you declare a global variable, and a called
> module uses the same variable.
[snip]
>>
>>What I'm expecting is that the variables "MORE", "TOTAL_LENGTH", and
>>"FILES" should retain the values being set within the while-loop but
>>they aren't.
>>
>>Any thoughts as to why?
>
>
> see my explanation above. If you need variables to exit, you need to
> set return values to handle those returns.
>
>
>>TIA,
>>Brad.
>>
>>P.S. The break command doesn't affect anything. If I comment it out
>>and let the loop run its course, all three variables resort back to
>>their original values exactly like when the break executes.
>
>
> All by design. Again, if you need the values to be maintained, you
> need to return() those values.
I don't do much scripting beyond expect, can you have more than one
return value to a script? I counted three desired variables. Is there
a way to get all three out without going to global?
In C, I would pass two by reference and return the third. Can you do
weird stuff like that in a script?
-- Alma
More information about the Linux-users
mailing list