查看磁盘使用TOP 10的脚本

查看磁盘使用TOP 10的脚本

用途: 根据指定目录,查找出目录下占用空间最大的top 10目录和文件
#!/bin/bash
#===============================================================================
# copyright by hwb
# date:2020-11-3
# USAGE: ./find_disk_usage.sh <directory> 
# 用途: 根据指定目录,查找出目录下占用空间最大的top 10目录和文件
#===============================================================================

#传参
bk_directory="/"
top_n=10

#调用函数库
[ -f /etc/init.d/functions ] && source /etc/init.d/functions
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
source /etc/profile

#Require root to run this script.
[ $(id -u) -gt 0 ] && echo "请用root用户执行此脚本!" && exit 1



#用第一个参数指定服务器目录
if [ -n "$1" ];then
   bk_directory=$1
   #判断目录是否存在,防止当路径不存在时rm -rf /*之类问题发生
   [ -d $bk_directory ] || echo "服务器目录[$bk_directory]不存在,请检查输入参数!"
   [ -d $bk_directory ] || exit 1
fi


function find_disk_usage(){
  echo ""
  echo -e "\033[33m************************File or directory [$bk_directory] disk usage top${top_n}************************\033[0m"
  temp_file=$( mktemp )
  
  if [ $bk_directory = "/" ];then
     bk_directory=""
  fi
    
  
  #开始统计文件大小
  top_count=1
  while read usage_m file_path
  do
	[[ -f $file_path ]] && file_type="File"||file_type="Directory"
	#fmt -w 80命令会将echo输出的整行数据根据其命令选项指定的宽度(120个字符)进行折行显示,再将折行后的数据以多行的形式传递给sed命令。 
    #sed在收到fmt命令的格式化输出后,将会在折行后的第一行头部添加两个空格,在其余行的头部添加一个加号和一个空格以表示差别。 
	echo -e "\e[1;32m Top.${top_count} ${usage_m}(MB)   ${file_type}   $file_path \e[1;32m" | fmt -w 120 | sed -e '1s/^/  /' -e '2,$s/^/+ /'
	top_count=$((top_count+1))
  done <<< "$( du -am ${bk_directory}/* 2>$temp_file|sort -nr|head -${top_n} )"
  
  #打印没有权限日志
  if [[ -s $temp_file ]];then
	cu_user=$( id|awk '{print $1}' )
	echo ""
	echo -e "\033[33m*************************用户 $cu_user没有以下文件/目录权限************************\033[0m"
	cat $temp_file
  fi
  
  #删除临时文件
  [[ -f $temp_file ]] && rm -f $temp_file
  echo ""
  echo -e "\033[33m*************************File or directory  disk usage Over!**************************\033[0m"
}


find_disk_usage

运行结果截图:

find_disk_usage.png

备份脚本下载:

find_disk_usage.zip

版权声明:
作者:WaterBear
链接:https://l-t.top/1070.html
来源:雷霆运维
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>