Counting files in folder without wc

5,065

Solution 1

It is giving the count as zero because you are increment count within a subshell. As such, the changes made to the variable are lost.

Instead say:

while read -r dir
do  
    count=$(($count + 1))
done < all_files

to achieve the desired result.

That said, parsing ls is never recommended.

Solution 2

You can use an array to hold the filenames and examine the array size:

files=( /root/Jamshed/script/* )
echo "${#files[@]}"

If you want all files recursively:

shopt -s globstar nullglob
files=( /root/Jamshed/script/** )
echo "${#files[@]}"

Solution 3

You can do it without parsing ls output or using wc as follows:

cd /root/Jamshed/script
count=0
shopt -s nullglob
for file in * .*[!.]*;do
    count=$(($count+1))
done
echo $count

Explanation

The glob pattern * will match all file and directory names not starting with a . and the glob pattern .*[!.]* will match all file and directory names whose name starts with a . and contains at least one non-. character (to avoid counting the special directories . and ..).

Share:
5,065

Related videos on Youtube

hamed golbahar
Author by

hamed golbahar

Updated on September 18, 2022

Comments

  • hamed golbahar
    hamed golbahar over 1 year

    Why does the following scripts give a count of 0 instead of giving the count of files present in the directory?

    #!/bin/bash
    cd /root/Jamshed/script
    count=0
    ls -lrt > all_files
    cat all_files | while read dir
    do  
        count=$(($count + 1))
    done
    echo $count;
    
  • Stéphane Chazelas
    Stéphane Chazelas about 10 years
    That would avoid counting ... and ..... as well. Note that the standard syntax is [!.], not [^.]. Note that in an empty directory, it would return 2.