This recipe based on ls
output format. When you list a directory, you see file types in the first column. “-” – for a plain file, “d” is for a directory. You can learn more about files in Unix in this article: “File and directory permissions in Linux / FreeBSD / MasOS“.
Also we use -c
flag of the grep
util. It counts all matches. ^
symbol in matching means “start of the line”.
Count number of files (not symbolic links, not char/block dev, etc):
ls -l . | grep -c '^-'
Bonus: count number of subdirectories in directory
ls -l . | grep -c '^d'
I think you got the idea.