奇怪的 Shell 行为

Weird Shell Behavior

好的。我正在尝试获取一些随机数据并将其加倍几次。所以,我:

sridhar@ip-10-118-18-248:/scratch$ for each in 1 2 3 4 5 6 7 8 9 10 ; do pv randomtext | cat >> randomtext ; cp randomtext "randomtext-${each}" ; ls -l randomtext* ; done
3.45KiB 0:00:00 [99.2MiB/s] [================================>] 100%
-rw-rw-r-- 1 sridhar sridhar 7070 Aug  6 22:09 randomtext
-rw-rw-r-- 1 sridhar sridhar 7070 Aug  6 22:09 randomtext-1
6.90KiB 0:00:00 [ 269MiB/s] [================================>] 100%
-rw-rw-r-- 1 sridhar sridhar 14140 Aug  6 22:09 randomtext
-rw-rw-r-- 1 sridhar sridhar  7070 Aug  6 22:09 randomtext-1
-rw-rw-r-- 1 sridhar sridhar 14140 Aug  6 22:09 randomtext-2
13.8KiB 0:00:00 [ 408MiB/s] [================================>] 100%
-rw-rw-r-- 1 sridhar sridhar 28280 Aug  6 22:09 randomtext
-rw-rw-r-- 1 sridhar sridhar  7070 Aug  6 22:09 randomtext-1
-rw-rw-r-- 1 sridhar sridhar 14140 Aug  6 22:09 randomtext-2
-rw-rw-r-- 1 sridhar sridhar 28280 Aug  6 22:09 randomtext-3
27.6KiB 0:00:00 [ 674MiB/s] [================================>] 100%
-rw-rw-r-- 1 sridhar sridhar 56560 Aug  6 22:09 randomtext
-rw-rw-r-- 1 sridhar sridhar  7070 Aug  6 22:09 randomtext-1
-rw-rw-r-- 1 sridhar sridhar 14140 Aug  6 22:09 randomtext-2
-rw-rw-r-- 1 sridhar sridhar 28280 Aug  6 22:09 randomtext-3
-rw-rw-r-- 1 sridhar sridhar 56560 Aug  6 22:09 randomtext-4
55.2KiB 0:00:00 [ 709MiB/s] [================================>] 100%
-rw-rw-r-- 1 sridhar sridhar 113120 Aug  6 22:09 randomtext
-rw-rw-r-- 1 sridhar sridhar   7070 Aug  6 22:09 randomtext-1
-rw-rw-r-- 1 sridhar sridhar  14140 Aug  6 22:09 randomtext-2
-rw-rw-r-- 1 sridhar sridhar  28280 Aug  6 22:09 randomtext-3
-rw-rw-r-- 1 sridhar sridhar  56560 Aug  6 22:09 randomtext-4
-rw-rw-r-- 1 sridhar sridhar 113120 Aug  6 22:09 randomtext-5
 110KiB 0:00:00 [ 989MiB/s] [================================>] 100%
-rw-rw-r-- 1 sridhar sridhar 226240 Aug  6 22:09 randomtext
-rw-rw-r-- 1 sridhar sridhar   7070 Aug  6 22:09 randomtext-1
-rw-rw-r-- 1 sridhar sridhar  14140 Aug  6 22:09 randomtext-2
-rw-rw-r-- 1 sridhar sridhar  28280 Aug  6 22:09 randomtext-3
-rw-rw-r-- 1 sridhar sridhar  56560 Aug  6 22:09 randomtext-4
-rw-rw-r-- 1 sridhar sridhar 113120 Aug  6 22:09 randomtext-5
-rw-rw-r-- 1 sridhar sridhar 226240 Aug  6 22:09 randomtext-6
24.7GiB 0:00:18 [1.15GiB/s] [==============================] 100000% ETA 0:00:00
^C

sridhar@ip-10-118-18-248:/scratch$

所以...为什么它在六次迭代中表现完全正常,然后突然,在第七次迭代中,它偏离比赛? bash、dash、ksh 和 zsh 中也会出现相同的行为。是什么赋予了?为什么它不继续将文件加倍十倍?在这种情况下,数字六有什么特别之处?

您正在读取一个文件并追加到同一个文件的末尾。当文件(相对)较小时,可以在写入任何内容之前一次性读取它,所以这不是问题,并且您会得到想要的行为。一旦超过一定大小,数据就会在读取端结束之前写入它 - 所以 reader 也会读取它,导致文件变得越来越长...