Shell script counts the number of directories and files in the current directory _linux shell

Source: Internet
Author: User

Linux how to count the current directory under the number of files, and how many directories?

Write a script with the shell below, put it in the current directory, and execute it.

Copy Code code as follows:

#!/bin/bash

#脚本名称 dir
#定义一个函数fun_directory

Fun_directory () {
Let "filenum=0"
Let "dirnum=0"

For I in $ (LS)
Todo
If [-D $i]
Then
Let Dirnum+=1
Else
Let Filenum+=1
Fi
Done

echo "The number of Directorys is $dirnum"
echo "The number of files is $filenum"

}

#调用函数

Fun_directory

Let's test:

Copy Code code as follows:

[Root@localhost scripts]# pwd
/root/scripts
[Root@localhost scripts]# ll |sort
Drwxr-xr-x 2 root root 4096 06-12 10:44 Charpter8
Drwxr-xr-x 2 root root 4096 06-13 12:34 AAA
-rw-r--r--1 root 06-13 08:56 file1
-rw-r--r--1 root 106 06-12 14:24 8-9
-rw-r--r--1 root root 121 06-12 09:36 JIU
-rw-r--r--1 root 06-13 11:09 Temp
-rw-r--r--1 root 210 06-12 13:40 8-8
-rw-r--r--1 root 222 06-12 11:51 8-6
-rw-r--r--1 root 247 06-12 11:35 8-5
-rw-r--r--1 root 273 06-12 13:13 8-7
-rw-r--r--1 root 292 06-12 10:57 8-1
-rw-r--r--1 root 309 06-12 14:51 8-11
-rw-r--r--1 root 314 06-12 15:01 8-17
-rw-r--r--1 root root 317 06-13 12:10 test
-rw-r--r--1 root 51 06-12 11:00 8-2
-rw-r--r--1 root 06-13 08:51 file
-rw-r--r--1 root 67 06-13 10:17 10-4
-rw-r--r--1 root 06-13 10:09 test.out
-rwxr-xr-x 1 root 103 06-12 11:06 8-3
-rwxr-xr-x 1 root 124 06-13 10:02 10-32
-rwxr-xr-x 1 root root 304 06-13 12:47 dir
-rwxr-xr-x 1 root 316 06-12 11:21 8-4
#执行脚本
[Root@localhost scripts]# sh dir
The number of Directorys is 2
The number of files is 20
[Root@localhost scripts]#

As you can see, data statistics are accurate.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.