getting variables out of while loop subshells

getting variables out of while loop subshells

Post by Keith All » Fri, 12 Jun 1998 04:00:00



This is actually a follow on to the latest UUOC discussion.  So, in sh
a while loop or a for loop spawns off as a subshell, and any variables
used therein are unavailable to the parent shell.  So, in something like

#!/bin/sh
#

count=0
export count

for filename in *
do
   *thing_to $filename
   count=`expr $count+1`
   echo $count
done

echo $count

While the script is in the for loop you see the counter incrementing,
but after the loop exits, you've had no effect on the value of $count
in the parent shell, which remains set at zero.  So is there any way
in sh to extract such a variable from a for loop?

-Keith Allen

_____________
Confused on my own time.  My employer pays me to be bewildered.

 
 
 

getting variables out of while loop subshells

Post by Douglas Wils » Fri, 12 Jun 1998 04:00:00




Quote:>for filename in *
>do
>   *thing_to $filename
>   count=`expr $count+1`
>   echo $count

ksh (not sh as requested):
    echo $count |&

Quote:>done

read -p cnt
>echo $count

Hope that helps,
Douglas Wilson

 
 
 

1. Variable in while loop not returning value outside the loop.?

#!/bin/bash

total=0

echo -n "Enter part of filename: "
read fnp

ls -ld *$fnp* 2> /dev/null | while read a b c d size e f g fname
do
   [ ! -f $fname ] && continue
   total=`expr $total + $size`
   echo $total
done

echo Total size of files containing the pattern \"$fnp\" is $total

_______________________________________________________________________

In the above code snippet, the last line always gives me value 0 for
the variable total.
But inside the loop the variable is having correct values (as
understood with the help of echo inside the loop). Can anybody explain
why $total in the last line of the code is always 0.

Also, Please suggest a solution for getting the value of $total (as
inside the loop) to be carried outside the loop too...

Thanks.

2. Calling C from Fortran: Function always returns zero?

3. 'While' loop starting a subshell?

4. gcc-i2.4.0p modified by Intel under Linux

5. Create variable named variable$i in for loop

6. Sending huge amount of mails by C program.

7. problem with for loop in subshell

8. AHA 2940 boot images?

9. `Nested (`Nested Subshells`) Subshells`

10. tcsh - to subshell or not to subshell

11. shell variables and subshells

12. variable scope: is a pipe a subshell ?

13. Using variables set in a bourne subshell