Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate over a set of folders in Windows Shell?

I'm currently trying to write a .cmd Windows Shell script that would iterate over a set of folders. However even the following simplest script:

echo "%ROOT%"
for %%f in ("%ROOT%\Binaries\" ) do (
    echo "%%f"
    if not exist "%%f\Subfolder"
        md "%%f\Subfolder"
)

outputs:

CurrentDir>echo "<ActualPathToRoot>"
"<ActualPathToRoot>"
%f\Subfolder was unexpected at this time
CurrentDir>if exists "%f\Subfolder"

What am I doing wrong? How do I alter that script so that it iterates over that one folder and once it see there's no subfolder named "Subfolder" it creates that subfolder? Also is there a good tutorial on writing such scripts?

like image 590
sharptooth Avatar asked Dec 07 '10 10:12

sharptooth


People also ask

How do you loop through all the 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).

How do I traverse a folder in command prompt?

To move back to the root directory type cd\ to get to the C:\> prompt. If you know the name of the directory you want to move into, you can also type cd\ and the directory name. For example, to move into C:\Windows>, type cd\windows at the prompt. How to change a directory or open a folder.


1 Answers

For (sub)folder-iteration you need to use a different for parameter.

So if you want to list all directories of C: you should do this:

for /d %%A in (C:\*) do echo %%A

Note the parameter /d which indicates a directory. To go into subdirectories you need to do a recursive for with /r

for /r C:\Windows %%A in (*.jpg) do echo %%A

This would iterate through all Windows subdirectories looking for JPGs. Low behold you should be able to do /d /r and this reference suggests you can - I simply can't, but maybe you are able to do this?

A workaround I quickly jotted down is to just do a dir of all directories in a for loop:

for /f "delims=" %%A in ('dir /ad/s/b') do echo %%A

Note that dir is used in conjunction with /ad/s/b which performs a recursive listing of directories, printing the names of the directories found.
With these tools in your hand you should be able to do your if-subfolder construct. Note that you might need

like image 153
Dennis G Avatar answered Sep 23 '22 16:09

Dennis G