Shell script to find the number of files present in the current directory without using WC command

by Vivek Gite on April 3, 2008 · 4 comments · [ vivek@nixcraft.com ]

#!/bin/bash
# Shell script to find the number of files present in the current
# directory without using WC command.
# NOTE/TIP:
# If allowed to use WC command then it should be as follows:
# ls | wc -l
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
FILE="/tmp/count.txt"
 
echo -n "Enter directory name : "
read dname
 
ls $dname > $FILE
 
echo "No of files in directory : $(grep [^*$] $FILE -c)"
rm -f $FILE
4000+ howtos and counting! If you enjoyed this article, join 45000+ others and get free email updates!

:( September 28, 2009

lol, rm -f $FILE ?

Reply

Jim October 8, 2009

The wc line in the comment should be:

ls | wc -l

(with a lower case l, not uppercase as you have it shown)

Reply

Jules February 10, 2010

It is lower case. Look at how the word “shell” is spelled a little higher.

Reply

Avinash K S February 3, 2011

#file1
ls > count
./file2 `cat count`

#file2
echo $#

Reply

Leave a Comment

You can use these HTML tags and attributes for UNIX commands or shell scripts: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 12 + 8 ?
Please leave these two fields as-is:
Are you a human being? Solve the simple math so we know that you are a human and not a script.



Tagged as: , , , , , ,