标签:bash script 删除空文件
写脚本操练时经常会创建一些空文件,所以就删除空文件这个小问题操练下,于是有了以下这个小脚本。
# 判断是否是目录,如果是目录,就返回0,否则返回1
is_directory(){
dir_path=$1
if [ -d $dir_path ] ;then
return 0
else
echo "$dir_path is not a directory."
return 1
fi
}
# 通过 file 命令判断文件是否是空文件
is_empty(){
file=$1
file_type=empty
mark=`file $file | cut -f 2 -d " "`
if [ "$mark" == "$file_type" ] ;then
return 0
else
return 1
fi
}
# 遍历目录中的文件,使用逻辑结构,如果是文档是空的,那么就必须执行 rm file 返回
# 值是删除文件的计数。
rm_empty_in_directory(){
current_dir=$1
count=0
for i in `ls $current_dir` ;do
is_empty $i && rm $i && let "count=$count+1"
done
#echo "count in function:$count"
return $count
}
rm_file_count=0
# 如果没有写入参数,就使用当前目录作为删除的目录。
if [ $# -eq "0" ] ;then
rm_empty_in_directory $PWD
# 调用函数的返回值也要使用变量$?来获取数值
temp=$?
rm_file_count=`echo "$rm_file_count + $temp" | bc`
else
# 写入参数,将参数作为需要删除的目录输入,遍历目录删除。
for dir in $@ ;do
if is_directory $dir ;then
temp=rm_empty_in_directory $dir
let "rm_file_count=$temp+$rm_file_count"
else
continue
fi
done
fi
echo "removed $rm_file_count files."标签:bash script 删除空文件
原文地址:http://liubaimoon.blog.51cto.com/9631203/1582606