我的要求是for循环的每个迭代都要写入for循环中引用的文件:
例如:
# 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
您可以在已有的位置完全扩展文件的当前内容`cat test`
。这就是为什么您可以在不影响循环的情况下写入同一文件的原因-循环不会继续读取文件,并且(原始)内容确实已经在内存中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句