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

#!/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
Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics:
CategoryList of Unix and Linux commands
File Management cat
Firewall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities dig host ip nmap
OpenVPN CentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Manager apk apt
Processes Management bg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searching grep whereis which
User Information groups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPN CentOS 8 Debian 10 Firewall Ubuntu 20.04
4 comments… add one
  • Avinash K S Feb 3, 2011 @ 11:55

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

    #file2
    echo $#

  • Jules Feb 10, 2010 @ 16:29

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

  • Jim Oct 8, 2009 @ 21:22

    The wc line in the comment should be:

    ls | wc -l

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

  • :( Sep 28, 2009 @ 22:02

    lol, rm -f $FILE ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.