重新认识du

最近因为要测试新一些新东西,又重新认识了一下du命令。我们知道du是来查看linux下文件大小的命令。加上-h可以用上单位,这样方便识别。

可这次查看的时候,明明才1GB大小的文件,居然显示是1.5G,这是du出问题了吗?

但是这个时候还不大确定是du的问题,还是文件系统的问题,于是用strace看了下,看了下就是du自己的问题,操作系统返回的就是正确的大小,du自己计算的时候给改了。

这个可麻烦了, 那就看下源码吧。 首先需要看下这个命令是哪个包提供的.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$ dnf provides du
Last metadata expiration check: 2 days, 2:39:35 ago on Fri 28 Jul 2023 07:59:35 PM CST.
coreutils-8.32-34.el9.x86_64 : A set of basic GNU tools commonly used in shell scripts
Repo : @System
Matched from:
Filename : /usr/bin/du

coreutils-8.32-34.el9.x86_64 : A set of basic GNU tools commonly used in shell scripts
Repo : baseos
Matched from:
Filename : /usr/bin/du

coreutils-single-8.32-34.el9.x86_64 : coreutils multicall binary
Repo : baseos
Matched from:
Filename : /usr/bin/du

这个在gnu网站上是可以直接下载的。

https://ftp.gnu.org/gnu/coreutils/coreutils-8.32.tar.gz

查了下du的源码是这样写的。可这个human_autoscale是什么意思不知道。

1
2
3
4
5
6
7
8
9
case 'h':
human_output_opts = human_autoscale | human_SI | human_base_1024;
output_block_size = 1;
break;

case HUMAN_SI_OPTION:
human_output_opts = human_autoscale | human_SI;
output_block_size = 1;
break;

还好 human.c文件里有写的比较清楚了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* Convert N to a human readable format in BUF, using the options OPTS.

N is expressed in units of FROM_BLOCK_SIZE. FROM_BLOCK_SIZE must
be nonnegative.

Use units of TO_BLOCK_SIZE in the output number. TO_BLOCK_SIZE
must be positive.

Use (OPTS & (human_round_to_nearest | human_floor | human_ceiling))
to determine whether to take the ceiling or floor of any result
that cannot be expressed exactly.

If (OPTS & human_group_digits), group the thousands digits
according to the locale, e.g., "1,000,000" in an American English
locale.

If (OPTS & human_autoscale), deduce the output block size
automatically; TO_BLOCK_SIZE must be 1 but it has no effect on the
output. Use powers of 1024 if (OPTS & human_base_1024), and powers
of 1000 otherwise. For example, assuming powers of 1024, 8500
would be converted to 8.3, 133456345 to 127, 56990456345 to 53, and
so on. Numbers smaller than the power aren't modified.
human_autoscale is normally used together with human_SI.

If (OPTS & human_space_before_unit), use a space to separate the
number from any suffix that is appended as described below.

If (OPTS & human_SI), append an SI prefix indicating which power is
being used. If in addition (OPTS & human_B), append "B" (if base
1000) or "iB" (if base 1024) to the SI prefix. When ((OPTS &
human_SI) && ! (OPTS & human_autoscale)), TO_BLOCK_SIZE must be a
power of 1024 or of 1000, depending on (OPTS &
human_base_1024). */

但是其实这个还是没有解决我的疑问。上面图里显示的是1.6G,但是du显示的是2.5G。按照上面暂时的,也应该是2G.