I'm trying to use an integer to count loop iterations, but after the loop is finished, the variable is blank. I've googled for clues, but no luck.
I have this code:
#!/bin/bash
declare -i count
echo entering loop
while read var
do
(( count++ ))
echo $count
done
echo exited loop
echo count is $count
When I run it interactively, pressing Ctrl+D after entering "c", I get output like this:
$ ./example
entering loop
a
1
b
2
c
3
exited loop
count is 3
But when I pipe input into the loop:
#!/bin/bash
declare -i count
echo entering loop
ls -la | while read var
do
(( count++ ))
# do something interesting here
echo $count
done
echo exited loop
echo count is $count
... I get output like this:
$ ./example
entering loop
1
2
3
4
5
exited loop
count is
$
Why doesn't it say "count is 5" here after exiting the loop?