0

I want to write a script that would count number of executable files in every folder in variable PATH. My code:

#!/bin/bash

IFS=":"
for directory in $PATH; do
        files=0
        ls -l $directory | while read rights x name group siz m d h name; do
                if [ `echo $rights | cut -c1` = "-" ]; then
                        files=$((${files}+1))
                fi
        done
        echo "Directory ${directory} contains ${files} executable files"
done

I want the echo to process after the end of the while loop and before the start of next for loop, but it always print out number of files = 0. The counting inside the if condition works.

jww
  • 97,681
  • 90
  • 411
  • 885
Spasitel
  • 169
  • 7
  • [Why *not* parse `ls`?](http://unix.stackexchange.com/questions/128985/why-not-parse-ls) – Cyrus Apr 22 '18 at 14:01
  • This can be one line of php, but as usual i will be downvoted by noobs. php is better than bash itself for bash scripts... in every aspects. – NVRM Apr 22 '18 at 14:55

1 Answers1

0

Have you considered using the find command? See this link. On GNU-based versions of find, something like the following should replace your ls call and while loop.

find $directory -type f -executable -print | wc -l

If you are worried about traversing subdirectories, you can use the maxdepth flag, i.e.

find $directory -maxdepth 1 -type f -executable -print | wc -l

For BSD-versions, again, see the link.

djkern
  • 452
  • 3
  • 11