#!/bin/bash
#Synopsis:用於統計腳本當前所在目錄或者用戶指定目錄下的所有文件類型及數量
#若直接運行腳本而不接任何命令行參數,則默認會統計腳本所在目錄下的文件
#Date:2016/10
#Author:Jian
#Usage:sh fileStat.sh /path1 /path2
testFile=$(mktemp /tmp/testfile.XXX)
#如果沒有指定查詢目錄,則使用默認的當前腳本所在目錄
if [ $# -eq 0 ]; then
path="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/"
else
path="$@"
fi
#在給出的所有目錄中循環查詢
for dir in $path
do
if [ ! -d $dir ]; then
#若給出錯誤路徑則用紅色字體打印出來
echo -e "\e[1;31m Error:wrong path [$dir] \e[0m"
continue
fi
#find命令遞歸查找指定目錄下面所有文件及目錄
find $dir -mindepth 1 -print | while read line
do
ftype="$(file -b $line)"
echo $ftype
done>$testFile
echo "==========Directory [$dir] File type and counts=========="
#使用awk關聯數組統計文件類型所對應的數目
awk '
{ count[$0]++ }
END{
for(ftype in count)
{ printf ("%s: %d\n",ftype,count[ftype]) }
}' $testFile | sort
#刪除創建的臨時文件
rm -rf $testFile
done