-4

How can I create a bash script to count the number of files in a directory using a loop.

The script should take a target directory and output: Number of files in ::

Zied
  • 1
  • 3
    Possible duplicate of [How to get the list of files in a directory in a shell script?](https://stackoverflow.com/questions/2437452/how-to-get-the-list-of-files-in-a-directory-in-a-shell-script) – Nick Jun 06 '17 at 17:56
  • I'm voting to close this question as off-topic because "gimme teh codez." Stack Overflow isn't a code-writing service. – EJoshuaS - Stand with Ukraine Jun 08 '17 at 04:46

3 Answers3

1
#!/bin/bash

counter=0

if [ ! -d "$1" ]
  then
    printf "%s\n" " $1 is not a directory"
    exit 0
fi

directory="$1"
number="${directory##*/}"
number=${#number}

if [ $number -gt 0 ]
  then
    directory="$directory/"
fi

for line in ${directory}*
  do
    if [ -d "$line" ]
       then
         continue
       else
         counter=$(( $counter + 1))
    fi
  done
printf "%s\n" "Number of files in $directory :: $counter"
D'Arcy Nader
  • 196
  • 5
  • 13
  • Suggested corrections: `for line in $1/*` (the / was omitted and the {} are superfluous) and `if [ -d "$line" ]` (the filename should be quoted incase of embedded whitespace). – cdarke Jun 06 '17 at 19:52
  • i did the corrections you suggested but i left the {directory}* you are right it's superfluos but i think it improves the redabilty. i also added a check on the existence of the slash. – D'Arcy Nader Jun 06 '17 at 20:38
1

I would use (GNU) find and wc:

find /path/to/dir -maxdepth 1 -type f -printf '.' | wc -c

The above find command prints a dot for every file in the directory and wc -c counts those dots. This would work well with any kind of special character (including whitespaces and newlines) in the filenames.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

You don't really need a loop. The following will count the files in a directory:

files=($(ls $1))
echo ${#files[@]}
codemonkey
  • 161
  • 1
  • 9