博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SHELL编程练习-获得指定目录下的所有文件及文件夹的大小
阅读量:7064 次
发布时间:2019-06-28

本文共 1906 字,大约阅读时间需要 6 分钟。

一、目的

编写一个脚本,可以获得指定目录下的所有文件及文件夹的大小。输出的样式与 ls -lh 命令相同。
命令执行示例,其中和 ls -lh 命令输出的唯一区别是目录的大小:
1.1、ls -lh命令的输出(注意目录大小)

[root@reedoracle ~]# ls -lh /root/dir1/total 24Mdrwxr-xr-x 3 root root 4.0K Feb  6 13:54 dir2drwxr-xr-x 2 root root 4.0K Feb  6 13:55 dir3-rw-r--r-- 2 root root    0 Feb  6 13:53 file1-rw-r--r-- 1 root root  23M Feb  6 13:54 file1-1-rw-r--r-- 2 root root    0 Feb  6 13:53 lfile1lrwxrwxrwx 1 root root    7 Feb  6 15:03 lfile2 -> file1-1

1.2、通过脚本实现的效果(注意目录大小)

[root@reedoracle dir1]# /root/newls.sh /root/dir1/drwxr-xr-x 4 root root 53M Feb  6 15:03 /root/dir1/drwxr-xr-x 2 root root 16M Feb  6 13:55 /root/dir1/dir3-rw-r--r-- 1 root root 15M Feb  6 13:55 /root/dir1/dir3/file3lrwxrwxrwx 1 root root 7 Feb  6 15:03 /root/dir1/lfile2 -> file1-1drwxr-xr-x 3 root root 15M Feb  6 13:54 /root/dir1/dir2drwxr-xr-x 2 root root 1.1M Feb  6 13:54 /root/dir1/dir2/dir2-2-rw-r--r-- 1 root root 1.0M Feb  6 13:54 /root/dir1/dir2/dir2-2/file2-2-rw-r--r-- 1 root root 13M Feb  6 13:54 /root/dir1/dir2/file2-rw-r--r-- 2 root root 0 Feb  6 13:53 /root/dir1/file1-rw-r--r-- 1 root root 23M Feb  6 13:54 /root/dir1/file1-1-rw-r--r-- 2 root root 0 Feb  6 13:53 /root/dir1/lfile1

二、难度

需要显示真实的目录大小,并且显示方式要与ls -lh样式一样
三、知识点
3.1、文件、目录操作知识
3.2、shell编程知识
四、思路与具体实现
4.1思路
1)首先判断是否输入参数
2)查找输入的参数所有的文件夹和文件
3)如果查找到的文件是目录类型,则通过du -sh统计目录大小,然后替换ls -lhd输出的大小,如果不是,则直接ls -lh显示。
4.2具体脚本

#!/bin/bash#function:new ls#author:reedFiles=$1if [ $# -eq 1 ];then        for FileList in $(find $1);do                FileType=$(ls -lhd $FileList |awk -F' ' '{print $1}'|cut -c 1)                if [ "$FileType" == d ];then                        DirSize=$(du -sh $FileList|awk '{print $1}')                        ls -lhd $FileList|sed "s/[^ ]\+/$DirSize/5"                else                        ls -lh $FileList                fi        doneelse        echo "--usage:$0 +[directory] or [file];"        echo "--example:$0 /root"fi

转载地址:http://xejll.baihongyu.com/

你可能感兴趣的文章
Java的接口总结
查看>>
C++复习
查看>>
cpsr与cpsr_c的区别
查看>>
星星评分
查看>>
Django - - Django REST framework基础:分页
查看>>
no module name cx_oracle 的解决方法
查看>>
poj - 2240 Arbitrage
查看>>
springmvc文件上传
查看>>
TypeScript 学习笔记
查看>>
Selenium3+python3-发送添加附件的邮件
查看>>
移动端-必要知识
查看>>
Redis指令
查看>>
Date12
查看>>
HTTP协议09-响应首部字段
查看>>
【原创】MySQL新旧版本ORDER BY 处理方法
查看>>
Cocos2d-x Eclipse下程序运行产生错误Effect initCheck() returned -1
查看>>
linux shell单引号、双引号及无引号区别(考试题答案系列)
查看>>
625某电商网站数据库宕机故障解决实录(下)
查看>>
创业公司感悟录之十个提醒—作者李天平
查看>>
.NET Project Open Day(2011.11.13)
查看>>