0

How do i keep a variable value after a while loop?

My intention here is to put a if clause within the while to count each time an operation has been done, but isn't working since the count resets after each while loop.

count=0

for file in $(ls /path)
do
   
   cat $ file | while read line
   do
      count=$((count+1))
      echo $count
   done

done

echo $count  #This echoes 0, even though the inner echo shows each sum.
Cyrus
  • 84,225
  • 14
  • 89
  • 153
culpinha
  • 55
  • 8
  • 1
    The problem is the pipe, not the loop: [Propagate value of variable to outside of the loop](https://stackoverflow.com/questions/7390497/propagate-value-of-variable-to-outside-of-the-loop) – JNevill Oct 06 '22 at 19:12

1 Answers1

0

There are many methods. In this case, it's probably easiest to drop the UUOC:

   while read line; do
      count=$((count+1))
      echo "$count"
   done < "$file"

which would be better written:

while read line; do echo "$((++count))"; done < "$file"

which would be even better written:

count=$(wc -l < "$file")

Although the last version sets count accurately (which the first two do not unless count is initialized) and does not emit the counts.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • I have to say William, i would never imagine that the problem was cat all along. I changed the code here and it worked perfectly, many thanks! – culpinha Oct 06 '22 at 19:15
  • The problem isn't really `cat`, the issue is the pipe. The pipe runs in a subshell, and any variables defined or changed are only changed in the subshell. – William Pursell Oct 06 '22 at 19:20