该命令按预期工作:
$(echo 10 > file.txt)cat file.txt; $(echo 5 > file.txt)cat file.txt
输出:
10
5
然而,这个却没有:
bash -c "$(echo 10 > file.txt)cat file.txt; $(echo 5 > file.txt)cat file.txt"
输出:
5
5
更奇怪的是这种行为:
bash -c "$(echo 10 > file.txt)cat file.txt; rm -f file.txt; $(echo 5 > file.txt)cat file.txt"
输出:
5
cat: file.txt: No such file or directory
甚至添加睡眠:
bash -c "$(echo 10 > file.txt)cat file.txt; sleep 1; rm -f file.txt; sleep 1; $(echo 5 > file.txt)cat file.txt"
你会得到一个科幻行为,与之前相同的输出:
5
# 2 seconds wait...
cat: file.txt: No such file or directory
命令的顺序几乎看起来像是从右到左。
这种奇怪的现象怎么可能被想象出来?
编辑:
@steeldriver 与 x
输入:
bash -c "$(echo 10 > file.txt)cat file.txt; $(echo 5 > file.txt)cat file.txt"
输出:
++ echo 10
++ echo 5
+ bash -c 'cat file.txt; cat file.txt'
5
5