您的位置:首页 > 运维架构 > Shell

编写一个SHELL脚本,可以获得指定目录下的所有文件及文件夹的大小。输出的样式与 ls -lh 命令相同。

2018-03-09 14:39 1111 查看
一、目的
编写一个脚本,可以获得指定目录下的所有文件及文件夹的大小。输出的样式与 ls -lh 命令相同。
命令执行示例,其中和 ls -lh 命令输出的唯一区别是目录的大小:
1.1、ls -lh命令的输出(注意目录大小)
[root@reedoracle ~]# ls -lh /root/dir1/
total 24M
drwxr-xr-x 3 root root 4.0K Feb  6 13:54 dir2
drwxr-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 lfile1
lrwxrwxrwx 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/file3
lrwxrwxrwx 1 root root 7 Feb  6 15:03 /root/dir1/lfile2 -> file1-1
drwxr-xr-x 3 root root 15M Feb  6 13:54 /root/dir1/dir2
drwxr-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:reed

Files=$1
if [ $# -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

done
else
echo "--usage:$0 +[directory] or [file];"
echo "--example:$0 /root"
fi
引用:SHELL编程练习-获得指定目录下的所有文件及文件夹的大小
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐