1、目的
編寫一個腳本,能夠得到指定目錄下的全部文件及文件夾的大小。輸出的樣式與 ls -lh 命令相同。
命令執行示例,其中和 ls -lh 命令輸出的惟一區別是目錄的大小:
1.一、ls -lh命令的輸出(注意目錄大小)shell
[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.二、經過腳本實現的效果(注意目錄大小)編程
[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
2、難度
須要顯示真實的目錄大小,而且顯示方式要與ls -lh樣式同樣
3、知識點
3.一、文件、目錄操做知識
3.二、shell編程知識
4、思路與具體實現
4.1思路
1)首先判斷是否輸入參數
2)查找輸入的參數全部的文件夾和文件
3)若是查找到的文件是目錄類型,則經過du -sh統計目錄大小,而後替換ls -lhd輸出的大小,若是不是,則直接ls -lh顯示。
4.2具體腳本bash
#!/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