mangusbrother
mangusbrother

Reputation: 4156

Batch Script loop recursively on directories, appending inital directory?

I have the following batch script

for /D /r %%f in ( %~dp0 ) do echo %%f

which should, as I understand it, Loop over all directories recusively in the directory storing the batch script, and print the full file path....

However, if the batch script is located in "C:\my\path" and under it there are folders "a", "a\b" and "a\b\c" I get the following output

C:\my\path\a\C:\my\path
C:\my\path\a\b\C:\my\path
C:\my\path\a\b\c\C:\my\path

What is wrong with this script?

Upvotes: 2

Views: 1168

Answers (3)

aschipfl
aschipfl

Reputation: 34909

That is because for does not access the file system to resolve the set in between the parentheses if there is no wildcard (*, ?) in it, so the string is returned literally.

Nevertheless, the file system is of course accessed to enumerate the directory tree given after /R.

Provide the root path for for /R after the switch /R and use global wildcards in the set. To search for directories rather than files, use the /D switch:

for /D /R "%~dp0" %%F in ("*.*") do echo %%~F

Do not forget to put quotation marks around path items to avoid trouble with whitespaces and other special characters. The ~ modifier of the for variable removes them in the loop body.


Alternatively, to return a pure directory list without any filtering, you can use the set ., like this:

for /R "%~dp0" %%F in (.) do echo %%~F

The output might look like this:

C:\my\path\a\.
C:\my\path\a\b\.
C:\my\path\a\b\c\.

Upvotes: 1

Compo
Compo

Reputation: 38604

Change your command thus to use the current directory.

FOR /D /R %%a IN (*) DO ECHO=%%a

Change your command thus to use the script directory.

FOR /D /R "%~dp0" %%a IN (*) DO ECHO=%%a

Upvotes: 1

MrTux
MrTux

Reputation: 33993

You seem to miss-use the for command:

for /D /r %~dp0 %%F in ( *.* ) do echo %%~F

The syntax for /R is:

FOR /R [[drive:]path] %%parameter IN (set) DO command 

See http://ss64.com/nt/for.html

Upvotes: 1

Related Questions