Linux Shell ディレクトリサイズスクリプト (du find)

Windows でディレクトリのサイズ合計を見せてくれるアプリがありますが、Linuxで同様のことがわかるシェルスクリプトを作ってます。
容量的に厳しくなってきたサーバーのファイル整理、無駄に溜まってる過去のログのチェックなどに使えると思います。

調べたいディレクトリをカレントにして、コマンドを実行。
shファイルのフルパスを指定する必要あるので、alias で設定しておけば便利と思います。

[ スクリプト ]

#!/bin/sh

#
# target directory file size summary list
#

tgt=`pwd`

echo ${tgt}
dirs=${tgt}/*

# loop current directory #
for filepath in ${dirs}; do
  # if filename belongs directory #
  if [ -d ${filepath} ]; then 
     
     # if excluded dir, do nothing. 
    if [ $# -eq 2 ] && [ $1 = "E" ] && [ $2 = ${filepath} ] ; then
      echo ${filepath}" ignored"
    else 
	  du -sh ${filepath}
    fi
    
    # if param count equals 1 and "C" #
    # print a file count # 
    if [ $# -eq 1 ]; then
      if [ $1 = "C" ]; then
        find ${filepath} | wc -l 
        echo "---------------------------------"
      fi
    fi
  fi 
done

[ 利用例 ]

引数なし

[root@???? opt]# /scriptdir/scriptname.sh
/opt
30M	/opt/firebird
190M	/opt/google
382M	/opt/openoffice4
700M	/opt/saw17
392M	/opt/sqlanywhere16

$1 : C
ファイル数も出力

[root@???? opt]# scriptdir/scriptname.sh C
/opt
30M	/opt/firebird
256
---------------------------------
190M	/opt/google
101
---------------------------------
382M	/opt/openoffice4
4275
---------------------------------
700M	/opt/saw17
1913
---------------------------------
392M	/opt/sqlanywhere16
2810
---------------------------------

$1 : E
$2 : 対象からはずすディレクトリ

[root@???? opt]# /scriptdir/scriptname.sh E /opt/google
/opt
30M	/opt/firebird
/opt/google ignored
382M	/opt/openoffice4
700M	/opt/saw17
392M	/opt/sqlanywhere16

コメントを残す