Shell Script Question

Brad De Vries devriesbj
Wed Jun 1 11:28:17 PDT 2005


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?

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?

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.



More information about the Linux-users mailing list