Issue
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.
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.
Answered By - William Pursell Answer Checked By - Marilyn (WPSolving Volunteer)