统计目录下文件大小的shell脚本实例
时间:2014-09-24 09:55 来源:linux.it.net.cn 作者:it
linux下统计目录中文件的大小,代码如下:
复制代码代码示例:
#!/bin/sh
# filename: df_dir.sh
#edit www.jbxue.com
usage(){
echo -e "\nUsage: `basename $0` DIRECTORY [MIN_SIZE]\n"
echo "Get file list of DIRECTORY, then output them in order by size."
echo "If MIN-SIZE is specified, only print those greater than MIN-SIZE.";
echo -e "MIN-SIZE is non-zero integer optionally followed by a k/K/m/M/g/G.\n";
exit
}
if [ $# -lt 1 ] || [ $# -gt 2 ]; then
usage
elif [ ! -d $1 ] ; then
echo -e "\nERROR: $1 is not a directory or does not exist\n"
exit
fi
## delete the slash at the end of directory name
## eg: /usr/share/ --> /usr/share
dir=${1%/}
## if MIN_SIZE is specified
if [ -n $2 ] ; then
## get the last char of MIN_SIZE
unit=${2: -1}
## get thE NUMBER part of MIN_SIZE except the unit
size=${2%?}
## if size is not an integer number, then exit
echo $size|awk '{if($0~/[^0-9]/) exit 1}'
[ $? -ne 0 ] && usage
case $unit in
g|G) msize=$[size * 1024 * 1024]
;;
m|M) msize=$[size * 1024]
;;
k|K) msize=$size
;;
[0-9]) msize=$2
;;
*) usage
;;
esac
else
msize=0
fi
du -s $dir/*|sort -rn|awk -v size=$msize '{\
if($1>1024*1024 && $1>size) printf "%5.1fG\t%s\n",$1/1024/1024,$2;\
else if($1>1024 && $1>size) printf "%5.1fM\t%s\n",$1/1024,$2;\
else if($1>size) printf "%5dK\t%s\n",$1,$2}'
用法: dfdir <目录> [最小文件大小,可省略,单位可为k/K/m/M/g/G, 默认为K]
说明: 大小超过1G的文件输出单位为G,超过1M的文件输出为单位为M
例1:
复制代码代码示例:
dfdir.sh /mnt/backup/lvm/
1.8 G /mnt/backup/lvm/win2kvm
330.7 M /mnt/backup/lvm/win2kvm.tar.bz2
36.0 K /mnt/backup/lvm/chkrootkit.tar.gz
例2:
复制代码代码示例:
dfdir.sh /usr/share 10m 显示大小超过10M的文件
29.1 M /usr/share/man
19.0 M /usr/share/gtk-doc
18.5 M /usr/share/locale
17.4 M /usr/share/themes
11.4 M /usr/share/fonts
例3:
复制代码代码示例:
dfdir.sh /bin 100 显示/bin下超过100K的文件
493K /bin/bash
160K /bin/tar
个人感觉,这个shell脚本写的不错,主要是多参数的灵活应用,方便输出想要的数据格式。
(责任编辑:IT)
linux下统计目录中文件的大小,代码如下:
复制代码代码示例:
#!/bin/sh
usage(){
if [ $# -lt 1 ] || [ $# -gt 2 ]; then
## delete the slash at the end of directory name
## if MIN_SIZE is specified
## get thE NUMBER part of MIN_SIZE except the unit
## if size is not an integer number, then exit
case $unit in
du -s $dir/*|sort -rn|awk -v size=$msize '{\ 用法: dfdir <目录> [最小文件大小,可省略,单位可为k/K/m/M/g/G, 默认为K] 说明: 大小超过1G的文件输出单位为G,超过1M的文件输出为单位为M 例1:
复制代码代码示例:
dfdir.sh /mnt/backup/lvm/
1.8 G /mnt/backup/lvm/win2kvm 330.7 M /mnt/backup/lvm/win2kvm.tar.bz2 36.0 K /mnt/backup/lvm/chkrootkit.tar.gz 例2:
复制代码代码示例:
dfdir.sh /usr/share 10m 显示大小超过10M的文件
29.1 M /usr/share/man 19.0 M /usr/share/gtk-doc 18.5 M /usr/share/locale 17.4 M /usr/share/themes 11.4 M /usr/share/fonts 例3:
复制代码代码示例:
dfdir.sh /bin 100 显示/bin下超过100K的文件
493K /bin/bash 160K /bin/tar
个人感觉,这个shell脚本写的不错,主要是多参数的灵活应用,方便输出想要的数据格式。 |