对于文件内容的循环是否保持文件打开,直到for循环完成?(Does for loop on a file content keeps the file opened until the for loop completes?)

我的要求是for循环的每次迭代,写入for循环中引用的文件:

对于Eg:

# cat test 1 2 3 4 5 6 # j=7; for i in `cat test`; do echo $j >> test; j=$(($j+1)); done # cat test 1 2 3 4 5 6 7 7 8 9 10 11 12 13

我觉得它有效。 但我想知道它是否有任何危险。 假设,如果我尝试使用awk写入同一个文件,它将无法工作:

# awk '{print $1+1'} test > test # cat test # awk '{print $1+1'} test >> test # cat test

因此,当我们使用for循环时,它是否会占用内存中的所有文件内容,因此,它不会导致任何问题?

更新:

我只知道strace命令,只有一点点用于调试。 有了它,我可以看到,似乎它使用内存:

read(255, "#!/bin/bash\nj=7; for i in `cat t"..., 76) = 76 rt_sigprocmask(SIG_BLOCK, NULL, [], 8) = 0 pipe([3, 4]) = 0 rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0 rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0 rt_sigprocmask(SIG_BLOCK, [INT CHLD], [], 8) = 0 clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f96dad589d0) = 17888 rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0 rt_sigaction(SIGCHLD, {0x43f2b0, [], SA_RESTORER, 0x332f832660}, {0x43f2b0, [], SA_RESTORER, 0x332f832660}, 8) = 0 close(4) = 0 read(3, "1\n2\n3\n4\n5\n6\n", 128) = 12

My requirement is for every iteration of for loop, to write to a file which is referred in the for loop:

For Eg:

# cat test 1 2 3 4 5 6 # j=7; for i in `cat test`; do echo $j >> test; j=$(($j+1)); done # cat test 1 2 3 4 5 6 7 7 8 9 10 11 12 13

I see it works. But I want to know if there are any dangers in it. For suppose, if I try to use awk to write to it same file, it won't work:

# awk '{print $1+1'} test > test # cat test # awk '{print $1+1'} test >> test # cat test

So, when we use for loop, does the it takes all contents of file in the memory and hence, it won't cause any issue?

Update:

I only know strace command and only a little bit for debugging. With it I could see, it seems it uses memory:

read(255, "#!/bin/bash\nj=7; for i in `cat t"..., 76) = 76 rt_sigprocmask(SIG_BLOCK, NULL, [], 8) = 0 pipe([3, 4]) = 0 rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0 rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0 rt_sigprocmask(SIG_BLOCK, [INT CHLD], [], 8) = 0 clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f96dad589d0) = 17888 rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0 rt_sigaction(SIGCHLD, {0x43f2b0, [], SA_RESTORER, 0x332f832660}, {0x43f2b0, [], SA_RESTORER, 0x332f832660}, 8) = 0 close(4) = 0 read(3, "1\n2\n3\n4\n5\n6\n", 128) = 12

最满意答案

您可以在`cat test`的位置完全展开文件的当前内容。 这就是为什么你可以在不影响循环的情况下写入同一个文件的原因 - 循环不会继续读取文件,并且(原始)内容确实已经在内存中了。

You fully expand the current contents of the file at the point where you have `cat test`. This is why you can write to the same file without affecting the loop – the loop does not keep reading from the file, and the (original) contents are indeed in memory already.

更多推荐