First, the purpose
Write a script to get the size of all the files and folders in the specified directory. The style of the output is
LS-LHcommand is the same.
Command execution example, where and
LS-LHThe only difference in command output is the size of the directory:
1.1. Output of LS-LH command
(note directory size)
[[email protected] ~]# 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. Effect through scripting (note directory size)
[[email protected] 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
Second, the difficulty
The actual directory size needs to be displayed and displayed in the same way as the LS-LH style
Third, knowledge points
3.1. Knowledge of file and directory operation
3.2. Shell Programming Knowledge
Iv. Thinking and concrete realization
4.1 Ideas
1) First determine if the input parameters
2) Find the input parameters for all folders and files
3) If the found file is a directory type, then the size of the LS-LHD output is du-sh by the size of the statistics directory, and if not, the direct LS-LH is displayed.
4.2 Specific scripts
#!/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
Shell programming Exercise-get the size of all files and folders under the specified directory