1

我正在尝试编写一个脚本来检查主文件夹磁盘使用情况,并在用户超过 xxGB 时通过电子邮件警告用户

我将 du -s * 的输出转储到临时文件中,逐行读取,当我尝试从 du 的输出中读取文件夹的大小和名称时,它无法正常工作,只需执行 echo $文件我将每行转储为两行,我尝试扩展以用空格替换制表符,但也没有用,而且我也不知道如何根据大小进行比较。

#!/bin/bash

#echo "Disk usage report for /homes on `hostname`"

EMAIL="helpdesk@xy.com"

##########################
# check staff
#########################

cd /homes/staff/
file1="/root/scripts/temp_check"
file2="/root/scripts/temp_check2"
du -s * | sort -rn | head -15  |awk '{print}' > $file1
expand $file1 > $file2

for line in $(cat $file2)

do

echo $line

# echo $line | awk '{ print $2 }'

mail -s "Disk usage report for your homefolder" $EMAIL

done
4

4 回答 4

3

为什么不简单地实现磁盘配额?几乎所有的 Unix/Linux 系统都可以做到这一点。

但是,如果您真的想这样做,为什么要进行所有的阴谋呢?

du - s *将产生一个两列输出,其中包含已使用的磁盘空间和用户名。使用 while 循环而不是将所有内容都放在临时文件中。

cd /home   #Or where ever all the user's home directories are stored
du -s | while read space user
do
    if [ $space -gt 10000000 ]
    then
        mailx -s"You're using a lot of diskspace!" $user <<MAIL
Dear $user:

We notice that you are now using $space in your home directory.
are you storing there? The total amount of diskspace allowed
is 15,000,000. We highly suggest you trim down your diskspace, or
we'll do it for you.

Sincerely,

Your Kindly System Administrator
MAIL
  fi
done   
于 2011-04-05T15:48:18.920 回答
1

The for loop is tokenizing your input based on spaces. So each word becomes a $line.

Instead of for loop, you can use a while loop to capture the input correctly, e.g.

cat $file2 | while read line; do echo $line; done

(You could add set -x to your script temporarily to see what's happening)

于 2011-04-05T15:17:37.837 回答
1

看看durep

在 Ubuntu 中安装 durep

使用以下命令安装 durep

sudo aptitude install durep

使用 durep

语法大致是durep [OPTION]… [DIRECTORY]

  • “durep -w ~/durepweb -td 2”</p>

    这将从当前目录开始到深度 2 的目录树打印到控制台,并在目录 ~/durepweb 中创建网页(此目录必须存在)。

于 2011-04-05T15:01:30.150 回答
0

如果你要求

 du -s /home/joe/* 

您会一一获得所有文件(隐藏文件除外)和目录的摘要,因为 * 由 shell 扩展。

 du -s /home/joe

会给你一行,总结一切,包括隐藏文件。

 du -s . 

也会总结整个目录 - 并将包括隐藏文件(刚刚测试过)。

由于它只是一条线,因此整条线从

 du -s * | sort -rn | head -15  |awk '{print}' > $file1

 du -s . >$file1 

因为您不需要对单行进行排序,将其减少到 15 行,然后使用 awk 语句重复它。

于 2011-04-05T15:29:58.940 回答