Shell Script Question

David Bandel david.bandel
Wed Jun 1 13:07:26 PDT 2005


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.

> 
> Here's my example:
> ------------
> typeset -i MAX_LEN=30 MORE=0 TOTAL_LENGTH=0 NEW_TOT_LEN
> FILES=
> 
> ls | while read FILE; do
>   # get the new total length = old total length + length(filename) + 1 (comma)
>   let NEW_TOT_LEN=${TOTAL_LENGTH}+${#FILE}+1
> 
>   # debug
>   echo -e "NEW_TOT_LEN=${NEW_TOT_LEN}\tLENGTH:${#FILE}\tFILE:${FILE}"
> 
>   # check if we've exceeded the maximum length allowed
>   if [ ${NEW_TOT_LEN} -gt ${MAX_LEN} ]; then
>     MORE=1
>     break
>   else
>     # generate comma-separated list of files
>     FILES="${FILES}${FILE},"
>     TOTAL_LENGTH=${NEW_TOT_LEN}
>   fi
> done
> 
> echo
> echo "MORE=${MORE}"
> echo "TOTAL_LENGTH=${TOTAL_LENGTH}"
> echo "FILES=${FILES}"
> ------------
> 
> 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.

Ciao,

David A. Bandel
-- 
Focus on the dream, not the competition.
            - Nemesis Air Racing Team motto



More information about the Linux-users mailing list