Counting directories and files

We can use a simple for loop to iterate over folder content and use an if statement to check whether the path is a directory or a file:

#!/bin/bash 
for path in /home/likegeeks/* 
do 
   if [ -d "$path" ] 
   then 
         echo "$path is a directory" 
   elif [ -f "$path" ] 
   then 
         echo "$path is a file" 
   fi 
done 

This is pretty straightforward script. We iterate over directory content and then we use an if statement to check whether the path is a directory or a file. Finally, we print beside each path whether it's a file or a directory.

We used quotes for the path variable because the file could contain a space.

Get Mastering Linux Shell Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.