二十一、编写简单脚本之检测磁盘空间
使用du命令
[root@tzPC 24Unit]# du -sh /home/* 12K /home/Christine
-S选项可以统计每个目录以及他们子目录的大小
[root@tzPC 24Unit]# du -Sh /var/log/ 38M /var/log/audit 28K /var/log/tuned 16K /var/log/samba/old 0 /var/log/samba/cores/smbd 0 /var/log/samba/cores 0 /var/log/samba
排序
-r选项允许按数字排序,-n选项从大到小排序
[root@tzPC 24Unit]# du -Sh /var/log/ | sort -rn 38M /var/log/audit 28K /var/log/tuned 16K /var/log/samba/old 2.1M /var/log/anaconda 2.0M /var/log/ 0 /var/log/samba/cores/smbd 0 /var/log/samba/cores 0 /var/log/samba 0 /var/log/rhsm
使用sed编辑器对结果添加行号
=命令添加行号,N命令让行号跟文本位于同一行,筛选前面11行结果
[root@tzPC 24Unit]# du -Sh /var/log/ | sort -rn | sed '{11,$D;=}' | sed 'N;s/\n/ /' 1 38M /var/log/audit 2 28K /var/log/tuned 3 16K /var/log/samba/old 4 2.1M /var/log/anaconda 5 2.0M /var/log/ 6 0 /var/log/samba/cores/smbd 7 0 /var/log/samba/cores 8 0 /var/log/samba 9 0 /var/log/rhsm
使用gawk命令给每行添加一个:给每行文本字段间放置一个制表符
[root@tzPC 24Unit]# du -Sh /var/log/ | > sort -rn | > sed '{11,$D;=}' | > sed 'N;s/\n/ /' | > gawk '{printf $1 ":" "\t" $2 "\t" $3 "\n"}' 1: 38M /var/log/audit 2: 28K /var/log/tuned 3: 16K /var/log/samba/old 4: 2.1M /var/log/anaconda 5: 2.0M /var/log/ 6: 0 /var/log/samba/cores/smbd 7: 0 /var/log/samba/cores 8: 0 /var/log/samba 9: 0 /var/log/rhsm
设置变量指定要监测的目录
CHECK_DIRECTORIES'"/var/log /home"
使用for循环遍历CHECK_DIRECTORIES变量每个目录,并使用du统计大小
for DIR_CHECK in $CHECK_DIRECTORIES do [...] du -Sh $DIR_CHECK [...] done
使用exec命令输出报告
DATE=$(date '+%m%d%y') exec > disk_space_$DATE.rpt
整个脚本如下
[root@tzPC 24Unit]# cat dir_check.sh #!/bin/bash CHECK_DIRECTORIES="/var/log /home" #Main Script DATE=$(date '+%m%d%y') exec > disk_space_$DATE.rpt echo "Top Ten Disk Space Usage" #前十磁盘空间使用 echo "for $CHECK_DIRECTORIES directories" for DIR_CHECK in $CHECK_DIRECTORIES do echo echo "The $DIR_CHECK Directory:" du -Sh $DIR_CHECK 2>/dev/null | sort -rn | sed '{11,$D;=}' | sed 'N;s/\n/ /' | gawk '{printf $1 ":" "\t" $2 "\t" $3 "\n"}' done exit
运行效果
[root@tzPC 24Unit]# bash dir_check.sh [root@tzPC 24Unit]# cat disk_space_090720.rpt Top Ten Disk Space Usage for /var/log /home directories The /var/log Directory: 1: 38M /var/log/audit 2: 28K /var/log/tuned 3: 16K /var/log/samba/old 4: 2.1M /var/log/anaconda 5: 2.0M /var/log 6: 0 /var/log/samba/cores/smbd 7: 0 /var/log/samba/cores 8: 0 /var/log/samba 9: 0 /var/log/rhsm The /home Directory: 1: 12K /home/tz-3 2: 12K /home/tz-2 3: 12K /home/tz-1 4: 12K /home/tz 5: 12K /home/Christine 6: 0 /home
学习来自:《Linux命令行与Shell脚本大全 第3版》第24章
今天的学习是为了以后的工作更加的轻松!