1

I am trying to get files from folders in batch. And this is the whole batch file:

for %%i in (folder) do echo (for /r "%%~i" %%j in (*.png) do echo %%~i-%%j)

The code executes as intended and outputs to console:

(for /r "folder" %j in (*.png) do echo folder-%j)

If i copy this and paste it as is to a cmd at the same path it echoes my file.

But if i remove the first echo from batch it outputs:

(for /R "%~i" %j in (*.png) do echo folder-%j )

Note that it doesn't execute the for loop and the second %%i is expanded but first is not. I can't get why this extremely basic one line batch doesn't work. Any help is appreciated.

  • Why the `echo` before the `for`? And for that matter why two `FOR` commands? – Squashman Apr 27 '20 at 20:57
  • `Echo` was for testing after the command didn't work. Two `For`s because i can add multiple folders at the `folder` in the first `for` loop. – Barış Sedefoğlu Apr 27 '20 at 20:59
  • As stated [here](https://stackoverflow.com/a/39653402) you cannot use a `for` meta-variable as the argument value of `for /R`; as a work-around, put the inner `for /R` loop into a sub-routine, call it by `call` and use an argument reference like `for /R "%~1" in ...`... – aschipfl Apr 27 '20 at 22:01
  • This might actually work. Thanks a lot. – Barış Sedefoğlu Apr 27 '20 at 22:01

1 Answers1

1

As mentioned here you cannot use a for meta-variable as an option value of for /R. This is because the options are read and parsed before for meta-variables are expanded. The for command, as well as the if and the rem command, is recognised earlier than other commands as described in this post; for meta-variables and delayed expansion are both expanded later, so they are read literally when these commands are parsed.

As a work-around, put the inner for /R loop into a sub-routine, call it by call and use an argument reference like %~1 to pass over the current value of the outer for loop:

for %%i in ("folder") do call :SUB "%%~i"
goto :EOF

:SUB
for /R "%~1" %%j in ("*.png") do echo "%~1"-"%%~j"
aschipfl
  • 33,626
  • 12
  • 54
  • 99