1

I want to write a shell script that compares the sizes of two directories X and Y, and reports which directory has more files and which directory has more subdirectories. So X and Y are two arguments.

I know the code for counting files in a directory is

ls -l | wc -l

I was having some trouble with the arguments and comparisons.

Also the same thing for subdirectories. I am new to shell scripting so any help would be appreciated.

3
  • Could you post any code that you've written or errors that you've received? As written your question is very broad.
    – Andy Jones
    Feb 2, 2015 at 21:57
  • find $dir1 -type d | wc -l should give you a count of directories, including $dir1 itself. find $dir1 -type f | wc -l will count regular files (not symlinks, devices, or whatever else). If you want disk space used by a directory, do du -s $dir1. Replace $dir1 with whatever path you want. Feb 2, 2015 at 22:01
  • ls -l | wc -l does not count files. It counts the lines of output produced by ls, some of which are probably files, some of which might be directories, and at least one of which is usally a header of some sort...
    – twalberg
    Feb 2, 2015 at 22:18

1 Answer 1

1

For files you can do:

filesX=$(find "${X}" -type f | wc -l)
filesY=$(find "${Y}" -type f | wc -l)

if (( filesX < filesY )); then
    echo "${Y} has more files"
elif (( filesX > filesY )); then
    echo "${X} has more files"
else
    echo "${X} and ${Y} have same number of files"
fi

For dirs it's basically the same:

dirsX=$(find "${X}" -type d | wc -l)
dirsY=$(find "${Y}" -type d | wc -l)

if (( dirsX < dirsY )); then
    echo "${Y} has more dirs"
elif (( dirsX > dirsY )); then
    echo "${X} has more dirs"
else
    echo "${X} and ${Y} have same number of dirs"
fi
1
  • Thanks Man! your code really helped1 Appreciate it a lot!
    – chillax786
    Feb 2, 2015 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.