开发者

unix shell globbing binding

If i have a do loop that looks something like

for file in *txt; do {something on $file that results in another file ending with txt being created}; done

Will that cause an infinite loop? I'm rath开发者_运维问答er afraid to test it.


The expansion of *.txt is typically done by the shell before any commands are run. So, no, it won't result in an infinite loop.

I say "typically" since it depends, of course, on the shell you're using. But every shell I've had experience with works this way, including bash as shown below:

pax$ rm -rf *.xyzzy ; touch 1.xyzzy 2.xyzzy ; ls *.xyzzy
1.xyzzy  2.xyzzy

pax$ echo ===== ; for i in *.xyzzy ; do
>    echo Processing $i
>    echo ..... before touch ; ls *.xyzzy
>    touch 3.xyzzy
>    echo ..... after touch ; ls *.xyzzy
>    echo =====
> done
=====
Processing 1.xyzzy
..... before touch
1.xyzzy  2.xyzzy
..... after touch
1.xyzzy  2.xyzzy  3.xyzzy
=====
Processing 2.xyzzy
..... before touch
1.xyzzy  2.xyzzy  3.xyzzy
..... after touch
1.xyzzy  2.xyzzy  3.xyzzy
=====

pax$ ls *.xyzzy
1.xyzzy  2.xyzzy  3.xyzzy

You'll note that the 3 file added during the first loop iteration doesn't affect the loop at all, because the expansion has already been done at that point.


No infinite loop is created because the glob expansion is done before the loop contents are handled.

If you ever want to try out something like this, check out ulimits and setup a conservative buffer of CPU time and processes to test with.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜