0

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 rather afraid to test it.

2 Answers 2

4

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.

1
  • This is also true in C shell. foreach i (*.xyzzy) ... end gives the same results as bash. Jul 7, 2011 at 3:04
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.