Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to keep a variable after a while loop bash

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading