1

I'm writing a bash script that uses a while loop to process over the rows outputted from a specific command. I also increment a variable (adding 1) for each row found.

Heres an example of the section of the script in question:

#!/bin/bash

count=0

ls | while read f
do 
  count=$(($count+1))
  echo "Count is at ${count}"
done

echo "Found total of ${count} rows"

Basically, it increments the $count variable just fine, but then when I print $count after the while loop.. its reset to 0..

Example output:

Count is at 1
Count is at 2
Count is at 3
Count is at 4
Count is at 5
Found total of 0 rows

Any idea why the $count would reset after the loops done?

I also tried adding the last echo statement using the && operator on the loop, like so:

count=0

ls | while read f
do 
  count=$(($count+1))
  echo "Count is at ${count}"
done && echo "Found total of ${count} rows"

With no success.

Any help would be appreciated

1
  • Don't parse the output of ls in any case; use for f in *; do instead. Commented Jun 29, 2016 at 18:42

1 Answer 1

2

A pipe spawns a subshell, use a process substitutions instead:

while read -r f
do 
  count=$(($count+1))
  echo "Count is at ${count}"
done < <(ls)

Also note that you shouldn't parse the output of ls.

And your example seems to count numbers of files and directories in current directory, which can be done with find and wc:

find -maxdepth 1 -mindepth 1 -printf "\n" | wc -l

or you can avoid ls with a for loop and globbing:

for f in * .*; do
  [ -e "$f" ] || continue
  count=$((count + 1))
  echo "Count is at ${count}"
done
Sign up to request clarification or add additional context in comments.

4 Comments

Note that both of your alternatives include hidden files, which the ls-parsing version does not.
Your first snippet using the < <() worked great! thank you. Can you tell me why I had to do that? and just piping it wouldnt work?
@Justin read the first linked page in the answer :-)
Thanks @andlrc, the second snippet in that link is exactly what I was looking for!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.