快速定位磁盘空间不足的问题

背景

在Linux系统使用/运维过程中,经常会遇到磁盘空间不足(或者使用率过高)的问题。
长期定位下来,积累了一些经验,我定位的方法一般如下(通常可以较快速地定位到问题所在)。

1. 大文件的存在

比如 查看在常见的一些目录如(/home, /root, /var/log)等下面是否存在一些较大的异常文件,总结命令如下:

# 如下命令查看一些目录中大于200MB大小的文件:
sudo find /var/log /home /root -type f -size +200M | xargs -i{} ls -sh {}

# 查找大于200MB的文件 并 按照文件占用磁盘空间大小排序:
sudo find /var/log /root /home /root -type f -size +200M -printf "%k KB \t%p\n" | sort -k1nr
sudo find /var/log /root /home /root -type f -size +200M -exec ls -Slh {} +
# WARNING! I use not -exec ... \;, but -exec ... {} +. This construction doesn't pluck every file just it was found, but it waits, while all files will be found, and then puts them to one command (this time — ls) as one big list of arguments. Then ls is looking at files and, because key -S, sorts them by size, largest first.

里面用的 ls -s 和 -S 选项,是需要注意的;同时 find 中的 -printf %k 选项 、 -exec 的用法,都是需要特别关注的。

man ls:
       -h, --human-readable
              with -l, print sizes in human readable format (e.g., 1K 234M 2G)
       -s, --size
              print the allocated size of each file, in blocks
       -S     sort by file size  (largest first 文件大的在前面)

man find:
       -printf format  : print  format  on  the  standard  output
              %k     The  amount of disk space used for this file in 1K blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file.
              %p     File's name.
              %s     File's size in bytes.

2. 有的大文件已删除了但进程未退出

另一种情况是,通过第1点中的find命令找不出来,但就是磁盘空间被占用太多,可能是因为有的大文件已经删除了,但却有进程打开着文件没有退出,导致文件虽表面已删除但却仍然占用磁盘空间。可以通过lsof 命令来查看deleted状态的文件,命令如下:

sudo lsof | grep 'deleted'

3. 可能存在一些太多的小文件

这种可能是某些程序异常在目录中写了很多的文件,加起来总量比较大。这方面比较case-by-case来分析,比如可以统计目录占用的磁盘空间,找出过大且不符合预期的。因为我较少遇到,该问题也不太典型,这里不详述。

相关文档:

Linux上的稀疏文件(用ls和du命令看到的大小不一样)


https://stackoverflow.com/questions/22598205/how-sort-find-result-by-file-sizes

master

Stay hungry, stay foolish.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

*