Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through all the files located under a certain path in zsh?

Tags:

Here's what I have so far:

for file in $(find /path/to/directory -type f); echo $file; done 

but I get this error:

zsh: parse error near `done' 
like image 334
Paul Baltescu Avatar asked Feb 19 '15 05:02

Paul Baltescu


People also ask

How do I loop all files in a directory in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).


1 Answers

There is no need to use find. You could try the following:

for file in /path/to/directory/**/*(.); do echo $file; done 

or

for file in /path/to/directory/**/*(.); echo $file 
  • the ** pattern matches multiple directories recursively. So a/**/b matches any b somewhere below a. It is essentially matches the list find a -name b produces.
  • (.) is a glob qualifier and tells zsh to only match plain files. It is the equivalent to the -type f option from find.
  • you do not really need double quotes around $file because zsh does not split variables into words on substitution.
  • the first version is the regular form of the for-loop; the second one is the short form without do and done

The reason for the error you get is due to the last point: when running a single command in the loop you need either both do and done or none of them. If you want to run more than one command in the loop, you must use them.

like image 103
Adaephon Avatar answered Sep 22 '22 00:09

Adaephon