本文共 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/