I was trying to iterate using a for over the output of ls -R, and it just hangs.
for i in $(ls -R /); do echo $i; done;
Is the same for
for i in $(find /); do echo $i; done;
Where is the problem? why keeps “the cursor waiting”?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The reason it pauses is because first the $() is treated as a variable to be calculated first. So it first does a find and loads all that into memory and then iterates over it.
Looping over a find tends to be a bad idea anyways. Even for small numbers of items. The bash for loop considers all whitespace to be delimiters for items. This means you will get undesirable results if any of your filenames contain spaces. Instead, I suggest using find’s built-in exec option.
As Karthik pointed out, you can also use a while loop with read.
This loop works for two reasons. First, read breaks on \n (or EOF) only. This means that files with whitespace will be counted as one file. Second, the pipe ensures that data does not build up. Filenames will be eaten by the loop as they are produced by ls.