在编写一个计算目录中消耗的块数量的简单函数时,我使用 du 检查是否得到了相同的答案。
为什么 ls 和 du 说这个文件占用了 16 个块?
#!/bin/bash
targetfile=/scratch/blob
rm -rf /scratch > /dev/null 2>&1
mkdir -p /scratch > /dev/null 2>&1
bs=$(dumpe2fs -h /dev/mapper/testvm-root 2> /dev/null | grep "Block size:")
bs=${bs/Block size:/}
bs=${bs// /}
echo blocksize=$bs
# create a file slightly too big for three blocks
dd if=/dev/zero of=$targetfile count=1 bs=$((bs*3+1)) > /dev/null 2>&1
echo "du says $(du $targetfile) units"
echo "du says $(du -b $targetfile) bytes:"
echo "ls says $(ls -s $targetfile) blocks"
echo "python says:"
python <(cat <<ENDMARKER
import os
import math
x = os.stat("$targetfile")
blocks=math.ceil(float(x.st_size)/float(x.st_blksize))
print("%d bytes st_blksize=%d, %d blocks " % (x.st_size,x.st_blksize,blocks))
print("blocksize=%d" % os.statvfs("$targetfile").f_bsize)
ENDMARKER
)
这是我所看到的:
blocksize=4096
du says 16 /scratch/blob units
du says 12289 /scratch/blob bytes:
ls says 16 /scratch/blob blocks
python says:
12289 bytes st_blksize=4096, 4 blocks
blocksize=4096
我希望 ls -s 能像 du -B 4096 一样说出 4 个块。